在默认的情况下切换 [英] Default in Switch case

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

问题描述

以下是code,我需要优化和计划,这将是很好的移动切换。但我可以的情况下,进行比较。所以我打算让comaparision(LEN> 3)作为默认情况。

如果我做比较的部分(LEN> 3)默认情况下,添加默认为第一开关等会是更快?

或者我如何才能让下面的code作为switch语句?

  IF(LEN> 3){
                    这将更加经常发生;
            }
            否则如果(LEN == 3){
                    接下来可能经常发生的情况下;
            }否则如果(LEN == 2){
                   下一个优先级的情况下;
            }其他{
                    这种情况很少发生;
            }


解决方案

大概不会。无论 IF ... ELSE 开关...情况下是高层次的结构。什么会降低你的分支prediction。更好的prediction是你的code将运行得更快。你应该把你最发生的情况下,第一个如果,第二次在否则,如果等等,就像你写的。对于开关的结果取决于内部编译器实现,尽管自己为了能重新排序的情况。在默认应实际留给较少出现的情况,因为条件的其余部分必须回落到默认前应检查。

要结束这一切,性能明智使用IF ... ELSE 是最优的,只要你按照正确的顺序设置的条件。关于开关...情况下这是编译器具体取决于所应用的优化。

另外请注意,开关...情况下如果...都更有限,因为它只支持值的简单比较。

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.

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

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;
            }

解决方案

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.

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.

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

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

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