performance with looping and count()ing

From: Date: Fri, 26 Mar 2004 18:45:38 +0000
Subject: performance with looping and count()ing
Groups: php.general 
Request: Send a blank email to php-general+get-181574@lists.php.net to get a copy of this message
hi. ok, so i've always been under the impression that count()ing during the expression of a loop was much inefficient when compared to count()ing just before the loop expression. GOOD: <?php $the_array_cnt = count($the_array); for($i = 0; $i < $the_array_cnt; $i++) { ... } ?> BAD: <?php for($i = 0; $i < count($the_array); $i++) { ... } ?> but then i did some tests and found that only on very large arrays is there any difference between the two. count()ing outside of the loop was only marginally better. i also tried performing the same operation using foreach() and it was slightly faster than count()ing within the loop and slightly slower than count()ing outside the loop. somone pointed out in a post to a message board that php handles the result of a count() in a special way and so it therefore does not need to count the array more than once each pass through the loop? can someone confirm? thanks, chris.

« previous php.general (#181574) next »