14

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:
 ...
}
Jose Vega
  • 10,128
  • 7
  • 40
  • 57

3 Answers3

13

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.

3

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).

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
3

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

Moishe Lettvin
  • 8,462
  • 1
  • 26
  • 40