note 46542 deleted from function.count by googleguy

From: Date: Mon, 17 Sep 2012 00:14:39 +0000
Subject: note 46542 deleted from function.count by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-190835@lists.php.net to get a copy of this message
Note Submitter: moazzam at ummah dot org ---- 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.

« previous php.notes (#190835) next »