PHP: foreach & while & for – Test de velocidad!

1 comentario

¿Cual de estos 3 bucles (foreach | while | for) php es el más rápido? bien, en este artículo vamos a hacer un test para controlar el tiempo de ejecución en segundos, que conseguimos con la función microtime().

En primer lugar, el código php de test:

$numero = 1500000;

// Generamos array
$array = array();
$i = 0;
while($i < $numero) {
  $array[] = $i++;
}

// Foreach
$tiempo = microtime(true);
foreach($array as $a) {
  $numeroulo = $a;
}
$tiempo_final = microtime(true);
$tiempo_foreach = $tiempo_final-$tiempo;
echo number_format($tiempo_foreach, 3, '.', '')
  ." segundos - foreach()\n";

// While
$tiempo = microtime(true);
$i = 0;
$longitud = count($array);
while($i<$longitud) {
  $numeroulo = $array[$i++];
}
$tiempo_final = microtime(true);
$tiempo_while = $tiempo_final-$tiempo;
echo number_format($tiempo_while, 3, '.', '')
  ." segundos - while()\n";

// For
$tiempo = microtime(true);
$longitud = count($array);
for($i=0;$i<$longitud;++$i) {
  $numeroulo = $array[$i];
}
$tiempo_final = microtime(true);
$tiempo_for = $tiempo_final-$tiempo;
echo number_format($tiempo_for, 3, '.', '')
  ." segundos - for()\n";

Y el resultado es:

0.139 segundos – foreach()
0.194 segundos – while()
0.187 segundos – for()

Podemos decir que el ganador en en cuanto a velocidad es foreach()

Este post ha sido archivado en PHP.

  • theonepro

    hola, lamento decirte esto,…

    prueba colocando la sección del código de foreach al final..

    ahora veras que el while es el más rápido por estar al inicio del código!.

    comprobado.!

¿Te ha sido útil?haz click en
+1https://plus.google.com/share?url=http://goo.gl/XP04M