user manual

Switch Statement Usage 21
22007E/0November 1999 AMD Athlon Processor x86 Code Optimization
Switch Statement Usage
Optimize Switch Statements
Switch statements are translated using a variety of algorithms.
The most common of these are jump tables and comparison
chains/trees. It is recommended to sort the cases of a switch
statement according to the probability of occurrences, with the
most probable first. This will improve performance when the
switch is translated as a comparison chain. It is further
recommended to make the case labels small, contiguous
integers, as this will allow the switch to be translated as a jump
table.
Example 1 (Avoid):
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");
}
Example 2 (Preferred):
int days_in_month, short_months, normal_months, long_months;
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");
}
Use Prototypes for All Functions
In general, use prototypes for all functions. Prototypes can
convey additional information to the compiler that might
enable more aggressive optimizations.