views:

2710

answers:

4

I was wondering if there was any difference in the way the following code was compiled into assembly. I've heard that switch-case is more efficient than if else, but in this example I am not quite sure if that would be the case.

if(x==1){
...
}else if(x==2){
...
}else{
...
}

and

switch(x){
 case 1:
 ...
 break;

 case 2:
 ...
 break;

 default:
 ...
}
+1  A: 

In this specific case, the switch can be turned into a jump table. The if statement (if you write your = as == :-P) could still do the same thing if the compiler could tell that x isn't changing between the if clauses (which is usually the case, unless x is volatile or something).

Chris Jester-Young
Those "==" always get me.
Jose Vega
+6  A: 

This has been asked before:

Greg Hewgill
Is the "exact duplicate" question the one about switch-vs-if for a 30-case switch when selecting one of two code-paths?
A: 

A compiler will sometimes turn a switch into a jump-table, if the entries are contiguous (or nearly so). Or it could theoretically use a binary search to find the case instead of a linear series of tests, which would be faster if you had a large number of cases.

On the other hand, there's nothing stopping the compiler from doing the same optimisations on the same code converted into if/else.

So on a good compiler, switch can be faster in some cases. On a very good compiler, they'd be the same.

+1  A: 

Note too that the if/else construct can be more efficient if you know certain cases are more likely than others.

Moishe
But switch cases are ordered, as well, no?
I don't know if all compilers guarantee the ordering. Also the compiler may create a jump table -- when this is more or less efficient than if/else is left as an exercise for the reader.
Moishe