FOR loop performance in PHP
As my research leads me to believe that for
loops are the fastest iteration construct in PHP... to make it clearer, which of the following do you think would be faster?
Example ONE
for ($i = 0; $i < count($myLargeArray); $i++ ) {
echo myLargeArray[$i];
}
Example TWO
$count = count($myLargeArray);
for ($i = 0; $i < $count; $i++ ) {
echo myLargeArray[$i];
}
My logic follows that on each iteration in example one accessing the length of myLargeArray on each iteration is more computationally expensive than accessing a simple integer value as in example two. Is that correct?
Solution 1:
The first way is slower because the count()
function has to be called in every iteration of the loop. The count()
method itself is pretty fast, but there is still some overhead in calling the function at all. By moving it outside the loop, you're performing what is called "loop invariant code motion", or sometimes "hoisting".
There's a whole family of optimizations like this that are interesting to learn about.
Having said all that, it seldom pays to stress about this very much. In your example here, the I/O of echoing the output is probably 10 times what you save through your "optimization". And if you do anything else at all inside your loop, your optimization means less and less.
I hate to be a wet blanket, but for more than 90% of your code, performance is a non-issue. Especially when you talk about web applications, which are more than 90% I/O to begin with.
Still, when you think your code is to blame, you should:
- Decide on the use case you need to optimize
- Measure your code performance
- Find the bottlenecks
- Identify the areas you can improve and decide whether it is worth your time to improve them.
- Make your code changes
- Go back to step 2
You'll nearly always discover that you need to improve your caching strategies and database optimization (which is just I/O optimization by another means), instead of twiddling code.
Solution 2:
The fastest construct in this case is actually the foreach loop:
foreach($myLargeArray as $element) {
echo $element;
}
The foreach() is also nice in that it'll always terminate, whereas a typo could leave you with an infinite loop when you use for().
Solution 3:
Example 2. Do not count the elements every iteration.
Updated: I've just been told that the value is precomputed:
nNumOfElements specifies how many values are currently stored in the array. This is also the number that
count($array)returns.
It seems to me the function count()
literally do nothing except wasting some microseconds and clock cycles (for those who know assembler).
Read here: Understanding PHP's internal array implementation (PHP's Source Code for PHP Developers - Part 4).
Perhaps you can try foreach range
:
foreach (range(0, (count(array)) as $number) {
echo $number;
}