Which Is Faster In Assembler, Switch-Case or If-Elseif

Started by
19 comments, last by Spoonbender 19 years, 7 months ago
Quote:Original post by Washu
Quote:Original post by Spoonster
Quote:Original post by antareus
You won't be able to tell which one is faster, and they may compile down to the same code anyway. Nano-optimization sucks, too.


Hah, that depends on the size of your switch statement, and how often you run it.

I could think of plenty of situations where it'd make a big difference. What if you're emulating a cpu? For every instruction, you need to look up its opcode, and you want that to go damn fast because, well, you do this for *every* emulated cycle.

Then don't use a switch or an if. There are much better ways of decoding instructions than a switch statement. table lookups combined with shifts for instance. Requires only a few if statements then.

Chances are that if you have a huge switch statement, or a huge set of if/else if/else you are looking at things wrong and may want to consider redesigning. There are, of course, cases where this isn't true, such as the Win32 WndProc.


Ok, it was just an example... ;)
But basically, I agree with you. Of course there are better ways to do it. The question is whether the compiler can figure them out. If it can, then the switch is definitely better than if-else-if. (although personally, I would probably do like you said, just to make sure.)
If the compiler is clever enough to build a jump table or do a binary search, then switch will be far faster than the if-else-if thing. And in that example, I wouldn't call it "nanooptimization" like someone said earlier. However, as iMalc said, premature optmization is just silly. In many cases, it doesn't matter whether you use switch, if's or build your own jump table or other clever systems, and all you should focus on is the readability of the code. But if you have a big switch in a performance-critical area of the code, then the question is pretty relevant.

This topic is closed to new replies.

Advertisement