Switch vs if else
Crossbones+ - Reputation: 20339
Posted 13 November 2012 - 06:46 AM
So I am going to openly take fault on saying it that way, using the word “never” inappropriately. It is a common quote that “--I” is never slow than, and sometimes faster than “I++”, and I derived my own quote from there.
But the overall message I feel is the same specifically because of what is in the parentheses. You can order the switch cases as easily as you can order if-else-else-else, and as of yet I haven’t seen compilers emitting any code that re-orders these, and that makes sense since the compiler can’t possibly predict what the human sees as the most common cases.
So ultimately the switch case’s order is no worse than the same person using an if-else-else, since that same person would not have changed the order for the switch case. Inside my parentheses, we assume an expert-level person is coding, but in the end as long as the logic between both the switch case and the if-else-else is the same and the coder, being an expert, tried to take advantage of each of their strengths, the output for the switch case would be the same as that of the if-else-else.
Once again I point out that the standard does not enforce this; this is just what I have observed over many compilers in person and not in-person during hacking. Every compiler that seems to be under the sun seems to work the same way on switch cases so it is easier just encompass that with the word “always”. It is basically a well understood algorithm for switch cases and is universally implemented across compilers because doing otherwise would leave that compiler at a disadvantage. I see no variations when looking at disassembly between any of the major compilers today that suggests any reason to compile to anything else, which suggests that it is both a well understood and fully solved problem that all compilers will implement.
Basically, the key point is within the parentheses, because anyone how knows how they both work as far as any compiler that actually is in use today works, they should be able to engineer a switch case that is never slower than an if-else-else-etc.
But the most key point is actually below that diatribe. Simply by not abusing switch cases or if-else-else you can gain both a performance increase and clearer and smaller code.
My Art: http://l-spiro.deviantart.com/gallery/4844241/Realism My Music: https://soundcloud.com/l-spiro
L. Spiro Engine: http://lspiroengine.com
L. Spiro Engine Forums: http://lspiroengine.com/forums