Optimizing Switch-Case Statements In C For Speed
Tuesday, October 28th, 2008Subscribe To Our Feed | Follow Us On Twitter | Get Updates on Email
The biggest bottlenecks in making efficient code today are jumps or branches. You must have always heard of people telling you to use switch-case blocks instead of cascadin if-else’es. They were right, but partially.
This is because a cascading if-else block will check for each condition in each iteration until it reaches the correct one. On the other hand, switch-case blocks are “supposed to” (why supposed to, we’ll see just now) just execute the correct statement and move on.
Optimization Technique 1: Keep the case label values close and small (Answer to “supposed to”)
Actually switch-case statements are also many times changed into if-else cascades by the compilers. This happens when the case label values are too far apart and/or are spread over a fairly large range. If you have a small switch-case statement like below, then the compiler will generate a jump-table instead of the if-else cascade.
switch(a) { case 0: /*do something*/ case 1: /*do something*/ case 2: /*do something*/ case 3: /*do something*/ default: }
A jump table is like a “lookup table” or a “dispatch table”. You can assume that compiler creates an internal array of addresses. The array is indexed by the case lable values and the value at that index is the address of instructions corresponding to that case.
Optimization Technique 2: Place those cases first which are more likely to occur
© Safer Code | Optimizing Switch-Case Statements In C For Speed
|
Liked this post? Get FREE Updates Subscribe to RSS feed |