Using count directly in loops/cycles is wrong (PHP)

Count is a PHP command that … counts all elements in an array, or properties in an object.
But when you need to use it in loops, first assign a new variable then use the variable in the loop. For example :

<?php
//size of $arr ~ 2000 elements
//WRONG variant (Time exec ~ 19 sec)

for($i=0;$i<count($arr);$i++) 
{
  
//... loop code here ...
}

//RIGHT variant(Time exec ~ 0.2 sec)
$arr_size=count($arr);
for(
$i=0;$i<$arr_size;$i++)
{
  
//...
loop code here ...
} ?>

 Another example :

<?php

for ($i=0; $i<10000; $i++) {
   
$arr[] = $i;
}

$time11 = microtime_float();
$bf = "";
for (
$i=0; $i<count($arr); $i++) {
   
$bf .= $arr[$i]."\n";
}
$time12 = microtime_float();
$time1 = $time12 - $time11;

print "First: ".$time1."\n";

$time21 = microtime_float();
$l = count($arr);
for (
$i=0; $i<$l; $i++) {
   
$bf .= $arr[$i]."\n";
}
$time22 = microtime_float();
$time2 = $time22 - $time21;

print "Second: ".$time2."\n";

?>

The output from the code above is (when run many times):

First: 0.13001585006714
Second: 0.099159002304077

First: 0.12128901481628
Second: 0.079941987991333

First: 0.18690299987793
Second: 0.13346600532532

As you can see, the second method (which doesnt use count() directly in the loop) is faster than the first method (which uses count() directly in the loop).

 

By moschos

This is me :)

Leave a Reply