As known, C# provides a few conditional control statements, the if–else if–else and the switch–case–default are the two most popular ones. Some people like the former but some others prefer the latter.
Some people adore the switch-case-default so much and cannot bear with both themselves and others to use if-else if-else and prove with both theories and samples. Some people do not care about their subtle differences and use whichever seems proper at right time.
Some tests have been done about the performance comparison between the if-else if-else and switch-case-default. Here are two:
Speed Test: Switch vs If-Else-If
Performance of If-else if tree vs. Switch (multiple variables) in C#
Some hot discussions have also been made on the stackoverflow forum. Here are a few:
Is there any significant difference between using if/else and switch-case in C#?
Is Switch (Case) always wrong?
Ways to eliminate switch in code
MSDN site also provides some deeper analysis about the two conditional control statements. Here is one.
Switch Statement vs. If-else if-else
After checking all these, I am still not convinced about which is good or bad but just get a bit more confused. So, I will still use both of them when I see appropriate in the future in that it must have reasons that they are both provided in C#. What about you?
According to this blog:
http://blogs.davelozinski.com/curiousconsultant/c-sharp-net-what-is-the-fastest-conditional-statement
the if/else, switch/case, and ternary ?: constructs all performance relatively the same.
However, once you start introducing nested switch/case statements, their performance starts to lag significantly.
Posted by: Watchingsite.wordpress.com | 02/06/2014 at 03:33 AM
Thanks for the link. The post has the most comprehensive analysis and testing about the statements we ever saw.
Posted by: Spiderinnet1 | 02/06/2014 at 02:17 PM
Yes but I feel it leaves out some of the more important decisions on which one to use.
A switch statement must use Same expression in every condition, equality is tested, and compared with a constant.
If statements are needed if nonconstant values are compared.
Typically switch statement expression are side effect free, so how many times have you evaluated a expression then looped 10,000,000 times to compare against constants?
For a switch statement order does not matter and a if statement is needed for ordering.
You can spend time looking at internals of each and IL produced, but I like SpiderInNet1 view as I understand it, to use which one makes code more readable and let the nerds worry about a few nanoseconds and if a application requires comparisons 10,000,000 times then take a closer look.
Posted by: JeffH | 02/19/2014 at 09:54 PM
JeffH, thanks a lot for the nice summary. I cannot agree more.
Posted by: Spiderinnet1 | 02/19/2014 at 11:21 PM