Page 1 of 1

switch..case and if..else

Posted: Mon Feb 20, 2006 4:17 am
by Neo
Which is better/more efficient?
IMHO Switch case looks more readable, but is it more efficient?

Re:switch..case and if..else

Posted: Mon Feb 20, 2006 4:19 am
by Solar
Depends on the number of if - else cascades, and the "smartness" of your compiler. switch - case can be implemented with lookup tables, but if - else could be optimized this way by a sufficiently smart compiler, too.

Starting somewhere around three cases, switch - case is also less error-prone (IMHO).

Re:switch..case and if..else

Posted: Mon Feb 20, 2006 5:25 am
by Pype.Clicker
with GCC, at least, all generated code i've seen for switches were quite satisfying to me ... sometimes when the "cases" are more compact (e.g. when it's exactly an ENUM with all cases present), i'd have been using a jump table and gcc still creates a "branch tree" instead ... i don't know what would actually have performed better (e.g. a branch table could incur a cache miss ... repeated "cmp <value>, <register>" normally do not suffer such issues.

Also, compared to "if (if ... else ...) else (if ... else ...)" a "case" instruction typically put all the "comparison" code ahead and _then_ the execution code, rather than jumping again-and-again over code blocks ... now better optimizers could detect your "if ... else if..." is actually a switch-like stuff...