“else if”是否比“switch()case”更快? [重复]

时间:2022-03-28 20:55:35

Possible Duplicate:
Is there any significant difference between using if/else and switch-case in C#?

可能重复:在C#中使用if / else和switch-case之间是否有任何显着差异?

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?

我问,因为我的程序有类似的结构(许多很多“其他如果”语句)。我应该把它们变成开关吗?

14 个解决方案

#1


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列表相比,所有项目都获得相同的访问时间,其中最后一个项目需要更长的时间才能到达,因为它必须首先评估每个先前的条件。

#2


Why do you care?

你为什么在乎?

99.99% of the time, you shouldn't care.

99.99%的时间,你应该不在乎。

These sorts of micro-optimizations are unlikely to affect the performance of your code.

这些微优化不太可能影响代码的性能。

Also, if you NEEDED to care, then you should be doing performance profiling on your code. In which case finding out the performance difference between a switch case and an if-else block would be trivial.

此外,如果您需要关心,那么您应该对代码进行性能分析。在这种情况下,找出switch case和if-else块之间的性能差异将是微不足道的。

Edit: For clarity's sake: implement whichever design is clearer and more maintainable. Generally when faced with a huge switch-case or if-else block the solution is to use polymorphism. Find the behavior that's changing and encapsulate it. I've had to deal with huge, ugly switch case code like this before and generally it's not that difficult to simplify. But oh so satisfying.

编辑:为清楚起见:实现更清晰,更易于维护的设计。通常,当遇到巨大的switch-case或if-else块时,解决方案是使用多态。找到正在改变并封装它的行为。我之前必须处理这样庞大,丑陋的开关案例代码,而且通常并不难以简化。但是太令人满意了。

#3


Believing this performance evaluation, the switch case is faster.

相信这种性能评估,开关盒更快。

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都不依赖于早期的情况,所以编译器能够以提供最快执行的方式重新排序测试。

#4


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.

另一件需要考虑的事情是:这真的是你的应用程序的瓶颈吗?在极其罕见的情况下,确实需要优化此类型。大多数情况下,您可以通过重新思考算法和数据结构来获得更好的加速。

#5


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),显示比较两者的基准测试。

#6


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)抛入该函数并在计时时循环几次。

#7


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语句中越好。

#8


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。

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。除非在一个非常紧凑的循环中,否则几乎没有写回家的瓶颈。

#9


Far more important than the performance benefits of switch (which are relatively slight, but worth noting) are the readability issues.

比开关的性能优势(相对轻微,但值得注意)更重要的是可读性问题。

I for one find a switch statement extremely clear in intent and pure whitespace, compared to chains of ifs.

与ifs链相比,我找到了一个非常明确的意图和纯空格的switch语句。

#10


I'm not sure, but i believe the speed of one or the other changes depending on the programming language you're using.

我不确定,但我相信一个或另一个的速度会根据您正在使用的编程语言而改变。

I usually prefer to use switch. That way the code is simplear to read.

我通常更喜欢使用开关。这样代码就很容易阅读。

#11


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.

如果可能,开关通常由编译器转换为查找表。所以查找任意一个案例是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链会慢一些。但是,根据您的情况被击中的频率,可能没有任何区别。

#12


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语句?

#13


Since the switch statement expresses the same intent as your if / else chain but in a more restricted, formal manner, your first guess should be that the compiler will be able to optimize it better, since it can draw more conclusions about the conditions placed on your code (i.e. only one state can possibly be true, the value being compared is a primitive type, etc.) This is a pretty safe general truth when you are comparing two similar language structures for runtime performance.

由于switch语句表达与if / else链相同的意图,但是以更受限制的,正式的方式,你的第一个猜测应该是编译器能够更好地优化它,因为它可以得出关于条件的更多结论你的代码(即只有一个状态可能是真的,被比较的值是原始类型等等)当你比较两个相似的语言结构以获得运行时性能时,这是一个非常安全的一般事实。

#14


see http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.switch%28VS.71%29.aspx

switch statement basically a look up table it have options which are known and if statement is like boolean type. according to me switch and if-else are same but for logic switch can help more better. while if-else helps to understand in reading also.

switch语句基本上是一个查找表,它有已知的选项,如果语句类似于布尔类型。根据我的开关和if-else相同,但对于逻辑开关可以帮助更好。而if-else也有助于在阅读中理解。

#1


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列表相比,所有项目都获得相同的访问时间,其中最后一个项目需要更长的时间才能到达,因为它必须首先评估每个先前的条件。

#2


Why do you care?

你为什么在乎?

99.99% of the time, you shouldn't care.

99.99%的时间,你应该不在乎。

These sorts of micro-optimizations are unlikely to affect the performance of your code.

这些微优化不太可能影响代码的性能。

Also, if you NEEDED to care, then you should be doing performance profiling on your code. In which case finding out the performance difference between a switch case and an if-else block would be trivial.

此外,如果您需要关心,那么您应该对代码进行性能分析。在这种情况下,找出switch case和if-else块之间的性能差异将是微不足道的。

Edit: For clarity's sake: implement whichever design is clearer and more maintainable. Generally when faced with a huge switch-case or if-else block the solution is to use polymorphism. Find the behavior that's changing and encapsulate it. I've had to deal with huge, ugly switch case code like this before and generally it's not that difficult to simplify. But oh so satisfying.

编辑:为清楚起见:实现更清晰,更易于维护的设计。通常,当遇到巨大的switch-case或if-else块时,解决方案是使用多态。找到正在改变并封装它的行为。我之前必须处理这样庞大,丑陋的开关案例代码,而且通常并不难以简化。但是太令人满意了。

#3


Believing this performance evaluation, the switch case is faster.

相信这种性能评估,开关盒更快。

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都不依赖于早期的情况,所以编译器能够以提供最快执行的方式重新排序测试。

#4


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.

另一件需要考虑的事情是:这真的是你的应用程序的瓶颈吗?在极其罕见的情况下,确实需要优化此类型。大多数情况下,您可以通过重新思考算法和数据结构来获得更好的加速。

#5


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),显示比较两者的基准测试。

#6


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)抛入该函数并在计时时循环几次。

#7


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语句中越好。

#8


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。

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。除非在一个非常紧凑的循环中,否则几乎没有写回家的瓶颈。

#9


Far more important than the performance benefits of switch (which are relatively slight, but worth noting) are the readability issues.

比开关的性能优势(相对轻微,但值得注意)更重要的是可读性问题。

I for one find a switch statement extremely clear in intent and pure whitespace, compared to chains of ifs.

与ifs链相比,我找到了一个非常明确的意图和纯空格的switch语句。

#10


I'm not sure, but i believe the speed of one or the other changes depending on the programming language you're using.

我不确定,但我相信一个或另一个的速度会根据您正在使用的编程语言而改变。

I usually prefer to use switch. That way the code is simplear to read.

我通常更喜欢使用开关。这样代码就很容易阅读。

#11


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.

如果可能,开关通常由编译器转换为查找表。所以查找任意一个案例是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链会慢一些。但是,根据您的情况被击中的频率,可能没有任何区别。

#12


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语句?

#13


Since the switch statement expresses the same intent as your if / else chain but in a more restricted, formal manner, your first guess should be that the compiler will be able to optimize it better, since it can draw more conclusions about the conditions placed on your code (i.e. only one state can possibly be true, the value being compared is a primitive type, etc.) This is a pretty safe general truth when you are comparing two similar language structures for runtime performance.

由于switch语句表达与if / else链相同的意图,但是以更受限制的,正式的方式,你的第一个猜测应该是编译器能够更好地优化它,因为它可以得出关于条件的更多结论你的代码(即只有一个状态可能是真的,被比较的值是原始类型等等)当你比较两个相似的语言结构以获得运行时性能时,这是一个非常安全的一般事实。

#14


see http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.switch%28VS.71%29.aspx

switch statement basically a look up table it have options which are known and if statement is like boolean type. according to me switch and if-else are same but for logic switch can help more better. while if-else helps to understand in reading also.

switch语句基本上是一个查找表,它有已知的选项,如果语句类似于布尔类型。根据我的开关和if-else相同,但对于逻辑开关可以帮助更好。而if-else也有助于在阅读中理解。