|
Hi everyone, I've heard that a stack of else if statements is faster than a switch statement .Is this true and if so why? From what I can tell they aren't that different.
(comments are locked)
|
|
The switch it usually faster for value types, and/or if the set of available inputs for the switch is widely distributed. (That is, a switch that has a case for the numbers 0-9 is generally faster than the comparable stack of ifs.) With that said, the performance differences likely won't be noticeable unless you have a huge stack of ifs or switch constantly executing - but at that point, you may be better off just using a different OOP design.
(comments are locked)
|
|
any theory would be just that, theory crafting. All C# code is translated into assembly by the compiler. the code could in fact look different in C# but be identical in assembly. there are TIMES where its faster specifically when it has to do less tests because the if statement could break earlier than a switch like if (i == 1) and i almost always is 1. The speed difference is meaningless unless your creating millions of lines of them. There may not be one depending on the compiler and its optimizations of your code. The if might break faster in some cases is why it might be better, it'll break faster than a switch possibly.
(comments are locked)
|
|
"The compiler can build jump tables where applicable. For example, when you use the reflector to look at the code produced, you will see that for huge switches on strings, the compiler will actually generate code that uses a hash table to dispatch these. The hash table uses the strings as keys and delegates to the case codes as values. This has asymptotic better runtime than lots of chained if tests and is actually faster even for relatively few strings." Konrad Rudolph PS: Google is your friend. I found that a long time ago before I posted this and what konrad is saying doesn't help me. I just want a simple answer.
Oct 12 '12 at 05:08 AM
DangerousBeans
(comments are locked)
|

http://stackoverflow.com/questions/445067/if-vs-switch-speed
This would explain better http://www.dotnetperls.com/if-switch-performance
The point is you can optimize a if/else if by putting first the most probable if and inside the condition if there would be many like:
if a more likely to be false,place it first. Reverse with :
if a is more likely then put it first.
The main drawback of switch is that they do not allow you to mix condition like:
This is not possible with a switch since it has only one condition.
I have myself once tried a benchmark about his with C and my if was actually faster.