views:

1029

answers:

7

Which one is better when performance is taken into consideration an if else if or switch case

Duplicate: http://stackoverflow.com/questions/395618/ifelse-vs-switch

+1  A: 

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

Damien
A: 

If you are using int/string/etc, then switch has some more complex jump options that might make switch more efficient if you have lots of conditions. However, the difference isn't likely to be huge, and switch isn't an option for all types (only integer-based, and string).

Marc Gravell
A: 

This is more a question of style than performance. Any performance difference will be neglibible, in my opinion. Also, see http://stackoverflow.com/questions/395618/ifelse-vs-switch.

HTH, Kent

Kent Boogaart
A: 

I've read that switch statements can be slightly faster.

Ben Alpert
A: 

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.

Jon Skeet
A: 

When addressing performance concerns, you have to measure the difference using realistic data. The fact that you're asking it from a speculative point of view suggests you don't have an actual performance issue to deal with, and therefore you should worry about which is more readable/maintainable

Giraffe
A: 

Tricky, you would have to run tests because if's and switches result in different IL code.

One would hope they were identical.

bleevo