Optimization for Faster Loops in PHP
As with all programming languages, in PHP there are always several ways to do something. As with most, there are differences in performance depending on how something is done – usually as a trade-off for code neatness. Take for example, running through an array.
$key = array_keys($aHash); $size = sizeOf($key); for ($i=0; $i<$size; $i++) $aHash[$key[$i]] .= "a";
Not particularly neat, but by far the fastest way to do the job. If we start to reduce the amount of code, we can find ourselves with this:
while(list($key) = each($aHash)) $aHash[$key] .= "a";
Although neater, the problem we’ve generated here is that for each time the loop runs, we’re relying on return values from the list() and each() functions. Our previous loop ran these at the start. Test have shown this method to be over 200% slower that our first version.
If we take this further, and use the notoriously inefficient foreach() function for our loop, we could be up to 600% slower than our original.
foreach($aHash as $key=>$val) $aHash[$key] .= "a";
So if the problem stems from the inclusion of unnecessary functions inside loops, the extent of it is linked to how long it takes those functions to execute. Comparing the two lines of code, one with the length of the array pre-calculated:
$size = count($array);
for ($i=0; $i<$size; $i++) {
and the other with an inline function:
for($i = 0; $i < count($array); $i++) {
It may surprise you to know that most tests put the latter at around five hundred times slower the former, and that's just using a simple count() function.
For more information on the various benchmarks mentioned within this post and others, see PHP Bench.
