switch statement vs if statement C#

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.

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.

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.

"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

Source here.

PS: Google is your friend.

Stacking switch/case statements is extremely slow.

Here’s a blog which benchmarks the if/else, switch/case, and ternary ?: operator against each other:

http://cc.davelozinski.com/c-sharp/what-is-the-fastest-conditional-statement

You’ll notice the nested switch/case statements comes out the slowest by far.