Skip to main content
IBM  
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 page 2 of 15


Looping, in various guises, is a fundamental concept in any programming language. It is very powerful, but can also cause performance problems in your programs.

Be careful which code you put inside a loop, especially if you expect the loop to be iterated through a large number (say, thousands) of times. In the next few panels, I look at several areas that require special attention when you use looping, whether the loops are for, foreach, while-do, do-while or any other form of loop. Broadly speaking, I consider each of the following:

  • Eliminating redundant function calls within loops.
  • Inlining function calls within loops.
  • Creating and destroying objects within loops.

Even though the focus is on the preceding types of optimizations within loops, the gains from any of the performance improvement techniques discussed in this tutorial will be multiplied by any large loops that are impacted.

Tip: You probably have tens, even hundreds of loops in your application. To identify which ones to focus your efforts on, insert some simple debug that outputs an identifying line each iteration. That way you can tell, for a variety of different sets of input data, just how many times each loop is executed. You might be surprised at the results!


Main menuSection menuFeedbackPreviousNext
Privacy Legal Contact