本文介绍了开关的情况下,如果VS其他的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否有在以下code编译成汇编的方式有什么不同。我听说的switch-case比别人是否更有效率,但在这个例子中,我不太清楚,如果这将是如此。

 如果(X == 1){
...
}否则如果(X == 2){
...
}其他{
...
}

 开关(X){
 情况1:
 ...
 打破; 案例2:
 ...
 打破; 默认:
 ...
}


解决方案

一个编译器有时会变成一个开关到一个跳转表,如果项是连续的(或接近)。或者,它理论上可以使用二进制搜索找到的情况下,而不是一个线性一系列的测试,如果你有一个大量的案件这将是更快的。

在另一方面,没有什么从做同一code相同的优化停止编译器转换成的if / else。

因此​​,对良好的编译器,开关可以是在某些情况下更快。在一个很好的编译器,他们会是相同的。

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:
 ...
}
解决方案

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.

这篇关于开关的情况下,如果VS其他的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-16 01:49
查看更多