Looping, in various guises, is a fundamental concept in any programming
language. It is very powerful, but can also cause performance problems in your
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
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