
Software Optimization Guide for AMD64 Processors | 25112 Rev. 3.06 September 2005 |
2.11Arranging Cases by Probability of Occurrence
Optimization
Arrange switch statement cases by probability of occurrence, from most probable to least probable.
Application
This optimization applies to:
•
•
Rationale
Arranging switch statement cases by probability of occurrence improves performance when the switch statement is translated as a comparison chain; this arrangement has no negative impact when the statement is translated as a jump table.
Example
Avoid switch statements such as the following, in which the cases are not arranged by probability of occurrence:
int days_in_month, short_months, normal_months, long_months;
switch (days_in_month) { case 28:
case 29: short_months++; break;
case 30: normal_months++; break;
case 31: long_months++; break;
default: printf("Month has fewer than 28 or more than 31 days.\n");
}
Instead, arrange the cases to test for frequently occurring values first:
switch (days_in_month) {
case 31: long_months++; break;
case 30: normal_months++; break; case 28:
case 29: short_months++; break;
default: printf("Month has fewer than 28 or more than 31 days.\n");
}
28 | C and C++ | Chapter 2 |