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

Matthew M. Osborn picture Matthew M. Osborn · Dec 28, 2008 · Viewed 87.6k times · Source

What is the benefit/downside to using a switch statement vs. an if/else in C#. I can't imagine there being that big of a difference, other than maybe the look of your code.

Is there any reason why the resulting IL or associated runtime performance would be radically different?

Related: What is quicker, switch on string or elseif on type?

Answer

ima picture ima · Dec 28, 2008

SWITCH statement only produces same assembly as IFs in debug or compatibility mode. In release, it will be compiled into jump table (through MSIL 'switch' statement)- which is O(1).

C# (unlike many other languages) also allows to switch on string constants - and this works a bit differently. It's obviously not practical to build jump tables for strings of arbitrary lengths, so most often such switch will be compiled into stack of IFs.

But if number of conditions is big enough to cover overheads, C# compiler will create a HashTable object, populate it with string constants and make a lookup on that table followed by jump. Hashtable lookup is not strictly O(1) and has noticeable constant costs, but if number of case labels is large, it will be significantly faster than comparing to each string constant in IFs.

To sum it up, if number of conditions is more than 5 or so, prefer SWITCH over IF, otherwise use whatever looks better.