note 46542 added to function.count
| From: | moazzamatummahdotorg at osu1 dot php dot net | Date: | Thu, 14 Oct 2004 23:59:41 +0000 |
| Subject: | note 46542 added to function.count | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-78559@lists.php.net to get a copy of this message | ||
This is an obvious note, but I am writing it any way so other, who did may not have observed this,
can take advantage of it too.
When running loops with count conditions, the code runs faster if you first assign the count() value
to a variable and use that (instead of using count() directly in a loop condition.
To explain my point better, here is an 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).
BTW: I copied the microtime_float() function from one of the comments in the microtime() section.
It just returns time with microseconds as float. Check comments in microtime() for more info.
----
Manual Page -- http://www.php.net/manual/en/function.count.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+46542
Delete -- http://master.php.net/manage/user-notes.php?action=delete+46542&report=yes
Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+46542&report=yes&reason=bad+code
Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+46542&report=yes&reason=spam
Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+46542&report=yes&reason=useless+example
Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+46542&report=yes&reason=contains+commercial+links
Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+46542&report=yes&reason=useless+note
Reject -- http://master.php.net/manage/user-notes.php?action=reject+46542&report=yes
Search -- http://master.php.net/manage/user-notes.php