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

查看:40
本文介绍了是“否则如果"吗?比“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天全站免登陆