Is quot;else ifquot; faster than quot;switch() casequot;?(是“否则如果比“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"快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是“否则如果"比“switch() case"快吗?


- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 输入按键事件处理程序 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01