Skip to main content
Shop Support Downloads
IBM Home Products Consulting Industries News About IBM
IBM developerWorks : Web Architecture : Education - Tutorials
Writing efficient PHP
ZIPPDF (letter)PDF (A4)e-mail
Main menuSection menuFeedbackPreviousNext
2. Writing efficient code

Optimizing loops: eliminate redundant function calls page 3 of 15

Function calls can be very expensive in terms of CPU usage. Try to reduce the use of them inside loops. The two primary ways to do this are:

  • Eliminate repeated calls to the same function with the same parameters
  • Inline small, simple functions

I'll look at inlining separately in Optimizing loops: inline function calls.

At first you may think, "Why would anyone repeatedly call the same function with the same parameters?" It's a reasonable question, but consider the following very common type of loop construct:

for ( $i=0; $i<count($myArray); ++$i )
   // do something

Although it appears innocent enough, that call to count($myArray) is made once every iteration. In any such loop, provided it doesn't add or remove elements from $myArray, the size of the array and hence the value returned by count($myArray) remains constant. You can write it more efficiently as follows:

$arraySize = count($myArray);
for ( $i=0; $i<$arraySize; ++$i )
   // do something

Notice how the call to count($myArray) is made just once now rather than once per iteration in the initial code example. This second approach does create another, temporary variable, but it gives better overall performance.

Main menuSection menuFeedbackPreviousNext
Privacy Legal Contact