Which is better/more efficient?
IMHO Switch case looks more readable, but is it more efficient?
switch..case and if..else
Re:switch..case and if..else
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).
Starting somewhere around three cases, switch - case is also less error-prone (IMHO).
Every good solution is obvious once you've found it.
- Pype.Clicker
- Member
- Posts: 5964
- Joined: Wed Oct 18, 2006 2:31 am
- Location: In a galaxy, far, far away
- Contact:
Re:switch..case and if..else
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...
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...