默认在开关情况下 [英] Default in Switch case

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

问题描述

下面是我需要优化和计划的代码,这将是很好的移动到切换。但我可以比较的情况下。所以我计划使comaparision(len> 3)作为默认情况。

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

如果我将比较部分(len> 3)作为默认情况,并在swith中添加默认为first,它会更快吗?

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

或者我如何使下面的代码作为switch语句?

Or how can I make the below code as 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;
            }


推荐答案

如果... else switch ... case 都是高级结构。你减慢了什么是分支预测。越好的预测就是代码运行得越快。你应该把你最多的情况放在第一如果,第二在 else if 等等, 。对于 switch 的结果取决于内部编译器实现,它可以重新排序的情况下,尽管你自己的顺序。 默认应实际保留用于较少发生的情况,因为必须检查其余条件,然后再返回 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 ... case 如果... else 更受限制,因为它只支持简单的值比较。

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

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

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