switch..case and if..else

Programming, for all ages and all languages.
Post Reply
User avatar
Neo
Member
Member
Posts: 842
Joined: Wed Oct 18, 2006 9:01 am

switch..case and if..else

Post by Neo »

Which is better/more efficient?
IMHO Switch case looks more readable, but is it more efficient?
Only Human
User avatar
Solar
Member
Member
Posts: 7615
Joined: Thu Nov 16, 2006 12:01 pm
Location: Germany
Contact:

Re:switch..case and if..else

Post 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).
Every good solution is obvious once you've found it.
User avatar
Pype.Clicker
Member
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

Post 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...
Post Reply