Which one is better when performance is taken into consideration an if else if or switch case
Duplicate: Is there any significant difference between using if/else and switch-case in C#?
For both readability and sense use a switch statement instead of loads of IF statements.
The switch statement is slightly faster though:
http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx (first hit on Google)
The compiler can optimise the switch statement so use that if you have more than, I would say, 3 or 4 different cases
What are you switching on? If you're switching on a string, the C# compiler either converts it into a dictionary or into a series of if/else checks. Which will be faster depends on the strings in question (including the candidate string).
If you're switching on an integral value, I believe the C# compiler always uses an IL switch statement - but that may or may not be faster than an if/else sequence depending on the values involved. (If they're in a large contiguous block, the CLR can just jump to the right place in the table - if they're very disparate, I suspect it doesn't help.)
Is this just an idle query, or are you really micro-optimising at this level? Any performance difference is going to be insignificant in the vast majority of cases - write for readability.
This is more a question of style than performance. Any performance difference will be neglibible, in my opinion. Also, see https://stackoverflow.com/questions/395618/ifelse-vs-switch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With