开关盒中的默认值

2022-01-19 00:00:00 c if-statement switch-statement c++

下面是我需要优化和计划的代码,它会很好地转移到 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.

相关文章