Chapter 2 C and C++ Source-Level Optimizations 31
Software Optimization Guide for AMD64 Processors
25112 Rev. 3.06 September 2005
2.14 Generic Loop Hoisting
Optimization
To improve the performance of inner loops, reduce redundant constant calculations (that is, loop-
invariant calculations). This idea can also be extended to invariant control structures.
Application
This optimization applies to:
• 32-bit software
• 64-bit software
Rationale and Examples
The following example demonstrates the use of an invarient condition in an if statement in a for
loop. The second listing shows the preferred optimization.
Listing 7. (Avoid)
for (i...) {
if (CONSTANT0) {
DoWork0(i); // Does not affect CONSTANT0.
}
else {
DoWork1(i); // Does not affect CONSTANT0.
}
}
Listing 8. (Preferred Optimzation)
if (CONSTANT0) {
for (i...) {
DoWork0(i);
}
}
else {
for (i...) {
DoWork1(i);
}
}
The preferred optimization in Listing 8 tightens the inner loops by avoiding repetitious evaluation of a
known
if control structure. Although the branch would be easily predicted, the extra instructions and
decode limitations imposed by branching (which are usually advantageous) are saved.