C# “else if”比“switch() case”快吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/767821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is "else if" faster than "switch() case"?
提问by Ivan Prodanov
I'm an ex Pascal guy, currently learning C#. My question is the following:
我是前 Pascal 人,目前正在学习 C#。我的问题如下:
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
....
And the switch:
和开关:
int a = 5;
switch(a)
{
case 1:
...
break;
case 2:
...
break;
case 3:
...
break;
case 4:
...
break;
default:
...
break;
}
Which one is faster?
哪个更快?
I'm asking, because my program has a similar structure (many, many "else if" statements). Should I turn them into switches?
我在问,因为我的程序具有类似的结构(很多很多“else if”语句)。我应该把它们变成开关吗?
采纳答案by Guffa
For just a few items, the difference is small. If you have many items you should definitely use a switch.
对于少数项目,差异很小。如果您有很多物品,则绝对应该使用开关。
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.
如果开关包含五个以上的项目,则使用查找表或哈希列表来实现。这意味着所有项目都获得相同的访问时间,与 if:s 列表相比,最后一个项目需要更多时间才能到达,因为它必须首先评估每个先前的条件。
回答by ólafur Waage
Shouldn't be hard to test, create a function that switches or ifelse's between 5 numbers, throw a rand(1,5) into that function and loop that a few times while timing it.
应该不难测试,创建一个在 5 个数字之间切换或 ifelse 的函数,将 rand(1,5) 放入该函数并在计时时循环几次。
回答by jfclavette
Technically, they produce the exact same result so they should be optimizable in pretty much the same way. However, there are more chances that the compiler will optimize the switch case with a jump table than the ifs.
从技术上讲,它们产生完全相同的结果,因此它们应该以几乎相同的方式进行优化。但是,与 ifs 相比,编译器使用跳转表优化 switch case 的可能性更大。
I'm talking about the general case here. For 5 entries, the average number of tests performed for the ifs should be less than 2.5, assuming you order the conditions by frequency. Hardly a bottleneck to write home about unless in a very tight loop.
我在这里谈论的是一般情况。对于 5 个条目,假设您按频率对条件进行排序,则为 ifs 执行的平均测试次数应小于 2.5。除非在一个非常紧凑的循环中,否则几乎不会成为写回家的瓶颈。
回答by Shaun Bohannon
I'd say the switch is the way to go, it is both faster and better practise.
我想说转换是要走的路,它既快又好。
There are various links such as (http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx) that show benchmark tests comparing the two.
有各种链接,例如 ( http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx) 显示比较两者的基准测试。
回答by Steven
Switch is generally faster than a long list of ifs because the compiler can generate a jump table. The longer the list, the better a switch statement is over a series of if statements.
Switch 通常比一长串 ifs 更快,因为编译器可以生成一个跳转表。列表越长,switch 语句优于一系列 if 语句。
回答by Michael Klement
Believing this performance evaluation, the switch case is faster.
相信这个性能评估,switch case更快。
This is the conclusion:
这是结论:
The results show that the switch statement is faster to execute than the if-else-if ladder. This is due to the compiler's ability to optimise the switch statement. In the case of the if-else-if ladder, the code must process each if statement in the order determined by the programmer. However, because each case within a switch statement does not rely on earlier cases, the compiler is able to re-order the testing in such a way as to provide the fastest execution.
结果表明,switch 语句的执行速度比 if-else-if 梯形图要快。这是由于编译器能够优化 switch 语句。在 if-else-if 梯形图的情况下,代码必须按照程序员确定的顺序处理每个 if 语句。然而,因为 switch 语句中的每个 case 不依赖于较早的 case,编译器能够以提供最快执行的方式重新排序测试。
回答by Joey
switch
usually gets translated into a lookup table by the compiler, if possible. So lookup of an arbitrary case is O(1), instead of actually doing a few case comparisons before finding the one you want.
switch
如果可能的话,通常会被编译器翻译成一个查找表。因此,查找任意案例是 O(1),而不是在找到您想要的案例之前实际进行一些案例比较。
So in many cases an if
/else if
chain will be slower. Depending on the frequency with which your cases are being hit that may make no difference, though.
所以在很多情况下if
/else if
链会更慢。不过,根据您的案件被击中的频率,可能没有任何区别。
回答by AnnaR
Short answer: Switch statement is quicker
简短回答:Switch 语句更快
The if statement you need two comparisons (when running your example code) on average to get to the correct clause.
if 语句平均需要两次比较(在运行示例代码时)才能找到正确的子句。
The switch statement the average number of comparisons will be one regardless of how many different cases you have. The compiler/VM will have made a "lookup table" of possible options at compile time.
无论您有多少不同的案例,switch 语句的平均比较次数都将是 1。编译器/VM 将在编译时制作可能选项的“查找表”。
Can virtual machines optimize the if statement in a similar way if you run this code often?
如果您经常运行此代码,虚拟机是否可以以类似的方式优化 if 语句?
回答by Vilx-
Another thing to consider: is this really the bottleneck of your application? There are extremely rare cases when optimization of this sort is really required. Most of the time you can get way better speedups by rethinking your algorithms and data structures.
另一件要考虑的事情:这真的是您的应用程序的瓶颈吗?在极少数情况下确实需要进行此类优化。大多数情况下,您可以通过重新思考算法和数据结构来获得更好的加速。
回答by annakata
Far more important than the performance benefits of switch (which are relatively slight, but worth noting) are the readability issues.
比 switch 的性能优势(相对较小,但值得注意)更重要的是可读性问题。
I for one find a switch statement extremely clear in intent and pure whitespace, compared to chains of ifs.
与 if 链相比,我发现 switch 语句的意图和纯空白非常清晰。