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

C#.NetSwitch Statement

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

In general (considering all languages and all compilers) a switch statement CAN SOMETIMES be more efficient than an if / else statement, because it is easy for a compiler to generate jump tables from switch statements. It is possible to do the same thing for if / else statements, given appropriate constraints, but that is much more difficult.

In the case of C#, this is also true, but for other reasons.

With a large number of strings, there is a significant performance advantage to using a switch statement, because the compiler will use a hash table to implement the jump.

With a small number of strings, the performance between the two is the same.

This is because in that case the C# compiler does not generate a jump table. Instead it generates MSIL that is equivalent to IF / ELSE blocks.

There is a "switch statement" MSIL instruction that when jitted will use a jump table to implement a switch statement. It only works with integer types, however (this question asks about strings).

For small numbers of strings, it's more efficient for the compiler to generate IF / ELSE blocks then it is to use a hash table.

When I originally noticed this, I made the assumption that because IF / ELSE blocks were used with a small number of strings, that the compiler did the same transformation for large numbers of strings.

This was WRONG. 'IMA' was kind enough to point this out to me (well...he wasn't kind about it, but he was right, and I was wrong, which is the important part)

I also made a bone headed assumption about the lack of a "switch" instruction in MSIL (I figured, if there was a switch primitive, why weren't they using it with a hash table, so there must not be a switch primitive.... ). This was both wrong, and incredibly stupid on my part. Again 'IMA' pointed this out to me.

I made the updates here because it's the highest rated post, and the accepted answer.

However,I've made it Community Wiki because I figure I don't deserve the REP for being wrong. If you get a chance, please up vote 'ima''s post.

Solution 3 - C#

The compiler is going to optimize pretty much everything into the same code with minor differences (Knuth, anyone?).

The difference is that a switch statement is cleaner than fifteen if else statements strung together.

Friends don't let friends stack if-else statements.

Solution 4 - C#

Three reasons to prefer the switch:

  • A compiler targeting native code can often compile a switch statement into one conditional branch plus an indirect jump whereas a sequence of ifs requires a sequence of conditional branches. Depending on the density of cases a great many learned papers have been written about how to compile case statements efficiently; some are linked from the lcc compiler page. (Lcc had one of the more innovative compilers for switches.)

  • A switch statement is a choice among mutually exclusive alternatives and the switch syntax makes this control flow more transparent to the programmer then a nest of if-then-else statements.

  • In some languages, including definitely ML and Haskell, the compiler checks to see if you have left out any cases. I view this feature as one of the major advantages of ML and Haskell. I don't know if C# can do this.

An anecdote: at a lecture he gave on receiving an award for lifetime achievement, I heard Tony Hoare say that of all the things he did in his career, there were three that he was most proud of:

  • Inventing Quicksort
  • Inventing the switch statement (which Tony called the case statement)
  • Starting and ending his career in industry

I can't imagine living without switch.

Solution 5 - C#

Actually, a switch statement is more efficient. The compiler will optimize it to a look up table where with if/else statements it cannot. The down side is that a switch statement can't be used with variable values.
You can't do:

switch(variable)
{
   case someVariable
   break;
   default:
   break;
}

it has to be

switch(variable)
{
  case CONSTANT_VALUE;
  break;
  default:
  break;
}

Solution 6 - C#

I didn't see anyone else raise the (obvious?) point that the supposed efficiency advantage of the switch statement is dependent on the various cases being approximately equally likely. In cases where one (or a few) of the values are much more likely, the if-then-else ladder can be much faster, by ensuring the most common cases are checked first:

So, for example:

if (x==0) then {
  // do one thing
} else if (x==1) {
  // do the other thing
} else if (x==2) {
  // do the third thing
}

vs

switch(x) {
  case 0: 
         // do one thing
         break;
  case 1: 
         // do the other thing
         break;
  case 2: 
         // do the third thing
         break;
}

If x is zero 90% of the time, the "if-else" code can be twice as fast as the switch-based code. Even if the compiler turns the "switch" into some kind of clever table-driven goto, it still won't be as fast as simply checking for zero.

Solution 7 - C#

often it will look better - ie will be easier to understand what's going on. Considering the performance benefit will be extremely minimal at best, the view of the code is the most important difference.

So, if the if/else looks better, use it, otherwise use a switch statement.

Solution 8 - C#

Side topic, but I often worry about (and more often see) if/else and switch statement get way too large with too many cases. These often hurt maintainability.

Common culprits include:

  1. Doing too much inside of multiple if statements
  2. More case statements than humanly possible to analyze
  3. Too many conditions in the if evaluation to know what is being looked for

To fix:

  1. Extract to Method refactoring.
  2. Use a Dictionary with method pointers instead of a case, or use an IoC for added configurability. Method factories also can be helpful.
  3. Extract the conditions to their own method

Solution 9 - C#

If you are just using if or else statement the base solution is using the comparsion ? operator

(value == value1) ? (type1)do this : (type1)or do this;

You can do the or routine in a switch

switch(typeCode)
{
   case TypeCode:Int32:
   case TypeCode.Int64:
     //dosomething here
     break;
   default: return;
}

Solution 10 - C#

As per this link, IF vs Switch comparison of iteration test using switch and if statement, is like for 1,000,000,000 iterations, Time taken by Switch Statement=43.0s & by If Statement = 48.0s

Which is literally 20833333 iterations per second, So, Should we really need to focus more,

P.S:Just to know the performance difference for small list of conditions.

Solution 11 - C#

This doesn't actually answer your question, but given there will be little difference between the compiled versions, I would urge you to write your code in a way that best describes your intentions. Not only is there a better chance of the compiler doing what you expect, but it will make it easier for others to maintain your code.

If your intention is to branch your program based on the value of one variable/attribute, then a switch statement best represents that intention.

If your intention is to branch your program based on different variables/attributes/conditions, then a if/else if chain best represents that intention.

I will grant that cody is right about people forgetting the break command, but almost as frequently I see people doing complicated if blocks where they get the { } wrong, so lines that should be in the conditional statement are not. It's one of the reasons I always include { } on my if statements even if there's one line in it. Not only is it easier to read, but if I need to add another line in the conditional, I can't forget to add it.

Solution 12 - C#

Interest question. This came up a few weeks ago at work and we found an answer by writing an example snippet and viewing it in .NET Reflector (reflector is awesome!! i love it).

This is what we discovered: A valid switch statement for anything other than a string gets compiled to IL as a switch statement. However IF it is a string it is rewritten as a if/else if/else in IL. So in our case we wanted to know how switch statements compare strings e.g is case-sensitive etc. and reflector quickly gave us an answer. This was useful to know.

If you want to do case-sensitive compare on strings then you could use a switch statement as it is faster than performing a String.Compare in an if/else. (Edit: Read https://stackoverflow.com/questions/94305/what-is-quicker-switch-on-string-or-elseif-on-type for some actual performance tests) However if you wanted to do a case-insensitive then it is better using a if/else as the resulting code is not pretty.

switch (myString.ToLower())
{
  // not a good solution
}

The best rule of thumb is to use switch statements if it makes sense (seriously), e.g:

  • it improves the readability of your code
  • you are comparing a range of values (float, int) or an enum

If you need to manipulate the value to feed into the switch statement (create a temporary variable to switch against) then you probably should be using an if/else control statement.

An update:

It is actually better to convert the string to uppercase (e.g. ToUpper()) as that has been apparently there are further optimizations that the just-in-time compiler can do as when compared to the ToLower(). It is a micro optimization, however in a tight loop it could be useful.


A little side note:

To improve the readability of switch statements try the following:

  • put the most likely branch first i.e. most accessed
  • if they are all likely to occur, list them in alphabetical order so it is easier to find them.
  • never use the default catch-all for the last remaining condition, that's lazy and will cause issues later on in the code's life.
  • use the default catch-all to assert an unknown condition even though it highly unlikely it will ever occur. that is what asserts are good for.

Solution 13 - C#

The switch statement is definitely the faster then a if else if. There are speedtest that have been supplied on it by BlackWasp

http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx

--Check it out

But depends heavily on the possibilities that you're trying to account for, but I try to use a switch statement whenever possible.

Solution 14 - C#

Not just C#, but all C-based languages, I think: because a switch is limited to constants, it's possible to generate very efficient code using a "jump table". The C case is really a good old FORTRAN computed GOTO, but the C# case is still tests against a constant.

It is not the case that the optimizer will be able to make the same code. Consider, eg,

if(a == 3){ //...
} else if (a == 5 || a == 7){ //...
} else {//...
}

Because those are compound booleans, the generated code has to compute a value, and shortcircuit. Now consider the equivalent

switch(a){
   case 3: // ...
    break;
   case 5:
   case 7: //...
    break;
   default: //...
}

This can be compiled into

BTABL: *
B3:   addr of 3 code
B5:
B7:   addr of 5,7 code
      load 0,1 ino reg X based on value
      jump indirect through BTABL+x

because you are implicitly telling the compiler that it doesn't need to compute the OR and equality tests.

Solution 15 - C#

My cs professor suggested not to you switch statements since so often people forgot the break or use it incorrectly. I can;t recall exactly what he said but something along the lines that looking at some seminal code base that showed examples of the switch statement (years ago) had a tons of mistakes in it also.

Solution 16 - C#

Something that I just noticed is that you can combine if/else and switch statements! Very useful when needing to check preconditions.

if (string.IsNullOrEmpty(line))
{
	//skip empty lines
}
else switch (line.Substring(0,1))
{
	case "1":
		Console.WriteLine(line);
		break;
	case "9":
		Console.WriteLine(line);
		break;
	default:
		break;
}

Solution 17 - C#

I Think Switch Is More Faster Than If Conditions like see if There is a program like :

Write a Program to enter any number (between 1 – 99) and check it is in which slot a) 1 – 9 then slot one b) 11 – 19 then slot two c) 21-29 then slot three and so on till 89-99

Then On If You Have Have To Make Many Conditions But Son Switch Case You Have TO Just Type >Switch ( no /10 ) > >and on case 0 = 1-9 ,case 1 = 11-19 and so on

it will Be So Easy

There Are Many More Such Examples Also!

Solution 18 - C#

a switch statement basicly is a comparison for equality. keyboard event's have a great advantage over switch statement's when having easy to write and read code then an if elseif statement would, missing a {bracket} could get troubling as well.

char abc;
switch(abc)
{
case a: break;
case b: break;
case c: break;
case d: break;
}

An if elseif statement is great for more then one solution if(theAmountOfApples is greater then 5 && theAmountOfApples is less then 10) save your apples else if(theAmountOfApples is greater then 10 || theAmountOfApples == 100) sell your apples. I dont write c# or c++ but I did learn it before I learned java and they are close languages.

Solution 19 - C#

One possible downside of switch statements is its lack of multiple conditions. You can have multiple conditions for the if (else) but not multiple cases statements with different conditions in a switch.

Switch statements are not suitable for logic operations beyond the scope of simple Boolean equations/expressions. For those Boolean equations/expressions, it is eminently suitable but not for other logic operations.

You have much more freedom with the logic available in If statements but the readability can suffer if the If statement becomes unwieldy or is handled poorly.

Both have there place depending on the context of what you are faced with.

Solution 20 - C#

My 2 cents on it. Well most of the times if performance is not a criteria than it's more about code readability. If the the number of if/else statements are too many than using switch statement is better.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatthew M. OsbornView Question on Stackoverflow
Solution 1 - C#imaView Answer on Stackoverflow
Solution 2 - C#Scott WisniewskiView Answer on Stackoverflow
Solution 3 - C#user1228View Answer on Stackoverflow
Solution 4 - C#Norman RamseyView Answer on Stackoverflow
Solution 5 - C#kemiller2002View Answer on Stackoverflow
Solution 6 - C#Mark BesseyView Answer on Stackoverflow
Solution 7 - C#gbjbaanbView Answer on Stackoverflow
Solution 8 - C#Chris BrandsmaView Answer on Stackoverflow
Solution 9 - C#Robert W.View Answer on Stackoverflow
Solution 10 - C#BretfortView Answer on Stackoverflow
Solution 11 - C#dj_segfaultView Answer on Stackoverflow
Solution 12 - C#DennisView Answer on Stackoverflow
Solution 13 - C#sleathView Answer on Stackoverflow
Solution 14 - C#Charlie MartinView Answer on Stackoverflow
Solution 15 - C#codyView Answer on Stackoverflow
Solution 16 - C#Even MienView Answer on Stackoverflow
Solution 17 - C#user3957230View Answer on Stackoverflow
Solution 18 - C#GeenView Answer on Stackoverflow
Solution 19 - C#Neil MeyerView Answer on Stackoverflow
Solution 20 - C#sudView Answer on Stackoverflow