是“否则如果"比“switch() case"快吗? [英] Is "else if" faster than "switch() case"?

查看:22
本文介绍了是“否则如果"比“switch() case"快吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是前 Pascal 人,目前正在学习 C#.我的问题如下:

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

下面的代码是不是比切换快?

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;


}

哪个更快?

我在问,因为我的程序具有类似的结构(很多很多else if"语句).我应该把它们变成开关吗?

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.

如果一个开关包含五个以上的项目,则使用查找表或哈希列表来实现.这意味着与 if:s 列表相比,所有项目都获得相同的访问时间,其中最后一个项目需要更多时间才能到达,因为它必须首先评估每个先前的条件.

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.

这篇关于是“否则如果"比“switch() case"快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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