IS"否则,如果"比&QUOT快;开关()情况下"? [英] Is "else if" faster than "switch() case"?

查看:165
本文介绍了IS"否则,如果"比&QUOT快;开关()情况下"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/395618/is-there-any-significant-difference-between-using-if-else-and-switch-case-in-c\">Is有在C#中使用if / else和开关外壳之间的任何显著区别?

我是一名前帕斯卡的家伙,目前正在学习C#。
我的问题是:

I'm an ex Pascal guy, currently learning C#. My question is the following:

低于code不是使开关速度更快?

Is the code below faster than making a switch?

    int a = 5;

    if (a == 1)
    {
        ....
    }
    else if(a == 2)
    {
        ....
    }
    else if(a == 3)
    {
        ....
    }
    else if(a == 4)
    {
        ....
    }
    else
        ....

和开关:

int a = 5;

switch(a)
{
    case 1:
        ...
        break;

    case 2:
        ...
        break;

    case 3:
        ...
        break;

    case 4:
        ...
        break;

    default:
        ...
        break;


}

哪一个是更快?

我问,因为我的程序具有相似的结构(很多很多否则,如果语句)。
我应该把他们变成交换机?

I'm asking, because my program has a similar structure (many, many "else if" statements). Should I turn them into switches?

推荐答案

有关短短的项目,两者差别不大。如果你有很多的项目,你绝对应该使用一个开关。

For just a few items, the difference is small. If you have many items you should definitely use a switch.

如果交换机包含超过5个项目,它使用一个查找表或哈希表来实现。这意味着,所有项目得到同样的访问时间,比起列表,如果:s其中的最后一个项目需要更多的时间才能达到,因为它必须首先评估每个previous条件

If a switch contains more than five items, it's implemented using a lookup table or a hash list. This means that all items get the same access time, compared to a list of if:s where the last item takes much more time to reach as it has to evaluate every previous condition first.

这篇关于IS&QUOT;否则,如果&QUOT;比&QUOT快;开关()情况下&QUOT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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