开关盒中的默认值 [英] Default in switch case

查看:16
本文介绍了开关盒中的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我需要优化和计划的代码,它会很好地转移到 switch 构造.但我可以比较case.所以我打算将比较 (len > 3) 作为 default 的情况.

The below is the code which I need to optimize and planned that it would be good to move to the switch construct. But I can compare in case. So I planned to make the comparison (len > 3) as the default case.

如果我将比较部分 (len > 3) 作为默认情况并将 default 添加为开关中的第一个,会更快吗?

If I make the comparison part (len > 3) as the default case and add the default as the first in the switch, will it be faster?

或者我怎样才能将下面的代码作为 switch 语句?

Or how can I make the below code as a switch statement?

if ( len > 3 ) {
    // Which will happen more often;
}
else if ( len == 3 ) {
    // Next case which may occur often;

} else if ( len == 2 ) {
    // The next priority case;

} else {
    // And this case occurs rarely;

}

推荐答案

可能不会.if...elseswitch...case 都是高级结构.让你慢下来的是分支预测.您的预测越好,您的代码运行速度就越快.您应该将最常见的情况放在第一个 if 中,第二个放在 else if 中,依此类推,就像您写的那样.对于 switch,结果取决于内部编译器实现,尽管您自己的顺序可以重新排序案例.default 实际上应该为发生较少的情况保留,因为在回退到 default 之前必须检查其余条件.

Probably not. Both if...else and switch...case are high-level constructs. What slows you down is the branch prediction. The better your prediction is the faster your code will run. You should put your most occurring case in first if, second in the else if and so on, just like you wrote. For switch the result depends on the internal compiler implementation which can reorder the cases despite your own order. The default should be actually reserved for the less occurring situations because rest of the conditions must be checked before falling back to default.

总而言之,只要您以正确的顺序设置条件,if...else 在性能方面的使用是最佳的.关于 switch...case,它是特定于编译器的,取决于应用的优化.

To conclude all this, performance-wise usage of if...else is optimal as long as you set your conditions in the correct order. Regarding switch...case it's compiler specific and depends on the applied optimizations.

另外请注意,switch...caseif...else 更受限制,因为它只支持简单的值比较.

Also note that switch...case is more limited than if...else since it supports only simple comparison of values.

这篇关于开关盒中的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆