问题
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 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.
回答2:
Note too that the if/else construct can be more efficient if you know certain cases are more likely than others.
回答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).
来源:https://stackoverflow.com/questions/195802/switch-case-vs-if-else