I am curious to know if anyone has looked into this but what is the benefit/downside to using a Switch statement vs. an If/Else in the .NET Framework, specifically in C#. I can't imagine there being that big of a difference, or than maybe the look of your code. Would be interested to see what everyone says.
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;
}
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.
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.
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.
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.
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.
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:
- Doing too much inside of multiple if statements
- More case statements than humanly possible to analyze
- Too many conditions in the if evaluation to know what is being looked for
To fix:
- Extract to Method refactoring.
- Use a Dictionary with method pointers instead of a case, or use an IoC for added configurability. Method factories also can be helpful.
- Extract the conditions to their own method
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.
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
if
s 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
.
To correct on 'Scott Wisniewski' answer (which is wrong on every aspect, but somehow got upvoted and accepted)
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.
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 http://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.
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.
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;
}
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 your trying to account for, but I try to use a switch statement whenever possible.
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.
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;
}