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 (continued) page 4 of 15

In addition to the previous common trap (see Optimizing loops: eliminate redundant function calls, also watch for code similar to the following:

$myConstString = "This is some constant text";
for ( $i=0; $i<$arraySize; ++$i )
   print trim(strtolower($myConstString));
   // do something

Provided the above loop does not modify $myConstString, then the call to trim(strtolower($myConstString)) will always return the same value (in this instance, a string). You can move this function call to just before the loop, and store the return value in a temporary variable.

One other thing to notice with this last example is that ordering of function calls can impact performance. For example, trimming white space off of a string then converting the result to lowercase is marginally more efficient than converting the same string to lowercase, then trimming off any white space. This is because trim may shorten the string, therefore resulting in less work for the strtolower function. Either way, the result should be the same in both cases. However, trimming first potentially results in less computational effort.

Watch for similar optimizations in your code.

Main menuSection menuFeedbackPreviousNext
Privacy Legal Contact