Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If else if or Switch case [duplicate]

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#?

like image 934
rahul Avatar asked Jan 02 '09 10:01

rahul


3 Answers

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

like image 109
Damien Avatar answered Nov 10 '22 03:11

Damien


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.

like image 38
Jon Skeet Avatar answered Nov 10 '22 02:11

Jon Skeet


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.

like image 44
Kent Boogaart Avatar answered Nov 10 '22 02:11

Kent Boogaart