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: inline function calls page 5 of 15

Often functions are defined that contain just one or two lines of code in the body. In this case, the overhead associated with calling and returning from the function may well be large compared to the actual work done by the function. Ideally, the compiler would detect this and replace the call to the function with the function body. Unfortunately, this rarely happens.

Languages such as C and C++ have an inline keyword to assist the compiler with this type of optimization. With PHP, however, it is necessary to perform this type of optimization manually. For example, consider the following code fragment:

function average( $a, $b )
   { return ($a + $b) / 2; }
for ( $i=0; $i<$arraySize; ++$i )
   $av[$i] = average( $array1[$i], $array2[$i] );

A more efficient implementation, albeit a little less desirable from a design and re-use perspective, moves the calculation out of the function average and into the caller. The result is:

for ( $i=0; $i<$arraySize; ++$i )
   $av[$i] = ( $array1[$i] + $array2[$i] ) / 2;

This second implementation eliminates the overhead associated with invoking the function average, and returning the result.

Only use this optimization for small functions and in places where the function could be called thousands of times. If you use this optimization technique for larger functions (where the overhead associated with invoking the function is dwarfed by the body of the function), the gains are minimal at the cost of far less readable and maintainable code.

Main menuSection menuFeedbackPreviousNext
Privacy Legal Contact