Linux Today: Linux News On Internet Time.

Optimizing Switch-Case Statements In C For Speed

Feb 02, 2009, 03:04 (6 Talkback[s])

[ Thanks to Safer Code for this link. ]

"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."

Complete Story

Related Stories: