O'Reilly logo

Core PHP Programming, Third Edition by Leon Atkinson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required