13

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:
 ...
}
4

3 回答 3

12

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.

于 2008-10-12T18:24:07.833 回答
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).

于 2008-10-12T18:18:34.130 回答
3

还要注意,如果您知道某些情况比其他情况更有可能发生,那么 if/else 结构会更有效。

于 2008-10-13T03:45:01.523 回答