28.20 Optimizing Loops
A very common performance mistake in PHP is creating loops that iterate over an array without caching the number of elements in the array. For example, consider Listing 28.12. The first loop can be optimized to perform about 50 percent faster by caching the value of count($arr) in a variable instead of calling count over and over again. You can even get the count inside the for loop's initialization step. Wherever possible, see if you can take static code, which is invariant of the loop's iterator, out of the loop.
Listing 28.12 Count array elements once
<?php
//setup sample array
$arr = array("Cosmo" , "Elaine", "George", "Jerry");
//loop over elements, recounting each time
for ($i=0; $i < count($arr); $i++)
{
print $arr[$i];
}
//loop over elements, make count first
$n = count($arr);
for ($i=0; $i < $n; $i++)
{
print $arr[$i];
}
//put count into init step
for ($i=0, $n = count($arr); $i < $n; $i++)
{
print $arr[$i];
}
?>
|