You are previewing Code Complete, Second Edition.

Code Complete, Second Edition

Cover of Code Complete, Second Edition by Steve McConnell Published by Microsoft Press
O'Reilly logo

Loops

Because loops are executed many times, the hot spots in a program are often inside loops. The techniques in this section make the loop itself faster.

Cross-Reference

For other details on loops, see Chapter 16.

Unswitching

Switching refers to making a decision inside a loop every time it's executed. If the decision doesn't change while the loop is executing, you can unswitch the loop by making the decision outside the loop. Usually this requires turning the loop inside out, putting loops inside the conditional rather than putting the conditional inside the loop. Here's an example of a loop before unswitching:

Example 26-6. C++ Example of a Switched Loop

for ( i = 0; i < count; i++ ) { if ( sumType == SUMTYPE_NET ) { netSum = netSum + amount[ i ...

The best content for your career. Discover unlimited learning on demand for around $1/day.