+1  A: 

The compiler can create a jump table for certain types of switch statements which is more efficient than just evaluating each element like a nested set of if statements. This is dependent on the type of switch and the language you are working in, but many C compilers just this sort of thing in their code generation.

So the short is that a switch can be more efficient but it depends on your particular usage.

Ukko
The compiler can create such a jump table from sets of if statements also.
nos
But to to that requires a huge amount of analysis and I just do not think that you can expect that to happen. If you start with a switch statement you are "switching" on a value that will be common to all the predicates. In the simple case like in C it might be a set of integer tags, but they are all integer tags. In the case of a set of if statements the compiler would have to derive that invariant. With a sufficiently smart compiler sure, but most of us have to work with predictably dumb compilers.
Ukko
Which dumb compilers are those ?
nos
I was being a bit facetious, but honestly all of them. You are looking at the classic SSC "Sufficiently Smart Compiler" argument which is totally bunk. Just because an optimization is possible and and analysis could theoretically be made to support it given an SSC in practice it is not worth the time. There are shelves full of clever optimizations that never made it into production because the cost of the analysis is too high compared to the benefit. The switch statement optimization might even fit this description today, however it was a historically important optimization still fielded.
Ukko
gcc/g++ does this easily, also for non trivial cases. It seems msvc does it too.
nos
Wow, color me impressed. I am going to date myself here but back 15 years ago when I was working on an optimizer for dynamic method dispatch in a language that used C as portable assembly that was not the case. We had to be careful how we generated the code to make sure we got the results we needed. I wonder if this is a result of the move to SSA form in GCC? This has the feel of the sort of thing that a compiler for a functional language would have gotten right and would have been special cased in a Dragon Book style C compiler. I still would not say it was done easily.
Ukko
+1  A: 

It doesn't matter unless you have a lot of cases. If you have a lot of cases then switch is better because the compiler generates a jump table for the items so the lookup is done in O(1) and not O(#cases). I also think that a switch is more readable than an if-else-if chain.

snakile