C++ switch case vs if else
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/195802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
switch case vs if else
提问by Jose Vega
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.
我想知道以下代码编译成程序集的方式是否有任何不同。我听说 switch-case 比 if else 更有效率,但在这个例子中,我不太确定是否会这样。
if(x==1){
...
}else if(x==2){
...
}else{
...
}
and
和
switch(x){
case 1:
...
break;
case 2:
...
break;
default:
...
}
回答by Jose Vega
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.
另一方面,没有什么可以阻止编译器对转换为 if/else 的相同代码进行相同的优化。
So on a good compiler, switch can be faster in some cases. On a very good compiler, they'd be the same.
所以在一个好的编译器上,在某些情况下 switch 会更快。在一个非常好的编译器上,它们是一样的。
回答by Moishe Lettvin
Note too that the if/else construct can be more efficient if you know certain cases are more likely than others.
另请注意,如果您知道某些情况比其他情况更有可能,则 if/else 构造可能会更有效。
回答by Chris Jester-Young
In thisspecific 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).
在这种特定情况下,switch
可以变成一个跳转表。如果编译器可以判断在子句之间没有变化(通常是这种情况,除非是或某事),则该if
语句(如果您将其编写=
为==
:-P)仍然可以做同样的事情。x
if
x
volatile