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 ...

Get Core PHP Programming, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.