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

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 :

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

//... loop code here ...

//RIGHT variant(Time exec ~ 0.2 sec)
loop code here ...
} ?>

 Another example :


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).


Tags PHP

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.