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?
for ($i = 0; $i < count($myLargeArray); $i++ ) {
echo myLargeArray[$i];
}
$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?
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:
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.
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With