PHP for loops and counting arrays
Posted September 7th, 2009 in PHP
It's well known that calling count($array) in a for loop in PHP is slower than assigning the count to a variable and using that variable in the for loop instead. However until recently, I wasn't aware that the assignment to a variable can be done in the for loop itself and share this here in this post.
The "wrong" way
The following example loops through an array in the variable $array:
for($i = 0; $i < count($array); $i++) {
// do something
}
The count() function is called on each loop which adds extra unecessary overhead. Even if the array only has a couple of items in it processing will still take longer than assigning count() to a variable.
The "right" way
Here's one way of doing it the "right" way:
$j = count($array);
for($i = 0; $i < $j ; $i++) {
// do something
}
The count is now assigned to the variable $j so the function is only called once.
Another way of doing the above is like so:
for($i = 0, $j = count($array); $i < $j ; $i++) {
// do something
}
The assignment $j = count($array) is part of the for loop, separated by a comma from the $i = 0 assignment. It is only called once at the start of the loop. It is not necesssarily superior to the first "right" example above but it does reduce the number of lines of code by one and means the purpose of the variable is clearly for of the loop.
Benchmarking
Out of interest I created an array with 100 elements and looped through the "wrong" way and the "right" way (and the whole thing 10,000 times for measurement purposes); the "right" way averaged about .20 seconds on my test box and the "wrong" way about .55 seconds.
Obviously these sorts of micro-optimizations aren't really going to have much of an effect on your own website (that .20 vs .55 seconds was looping through the test 10k times, remember) but it is interesting to see the differences.
Related posts:
- PHP for loops with multiple statements in each expression (Wednesday, October 20th 2010)
- Using + to merge arrays with PHP (Monday, October 26th 2009)
- Reading through a directory with PHP (Thursday, June 18th 2009)
- Create a CSV file from MySQL with PHP (Sunday, April 12th 2009)
- PHP IMAP: Looping through messages to find a specific subject (Thursday, March 5th 2009)
- Intialise an array in PHP with default values (Tuesday, October 7th 2008)

Comments
blog comments powered by Disqus