Is "else if" faster than "switch() case"?

C#PerformanceIf StatementSwitch Statement

C# Problem Overview


I'm an ex Pascal guy, currently learning C#. My question is the following:

Is the code below faster than making a switch?

int a = 5;

if (a == 1)
{
    ....
}
else if(a == 2)
{
    ....
}
else if(a == 3)
{
    ....
}
else if(a == 4)
{
    ....
}
else
    ....

And the switch:

int a = 5;

switch(a)
{
    case 1:
        ...
        break;

    case 2:
        ...
        break;

    case 3:
        ...
        break;

    case 4:
        ...
        break;

    default:
        ...
        break;


}

Which one is faster?

I'm asking, because my program has a similar structure (many, many "else if" statements). Should I turn them into switches?

C# Solutions


Solution 1 - C#

For just a few items, the difference is small. If you have many items you should definitely use a switch.

If a switch contains more than five items, it's implemented using a lookup table or a hash list. This means that all items get the same access time, compared to a list of if:s where the last item takes much more time to reach as it has to evaluate every previous condition first.

Solution 2 - C#

Why do you care?

99.99% of the time, you shouldn't care.

These sorts of micro-optimizations are unlikely to affect the performance of your code.

Also, if you NEEDED to care, then you should be doing performance profiling on your code. In which case finding out the performance difference between a switch case and an if-else block would be trivial.

Edit: For clarity's sake: implement whichever design is clearer and more maintainable. Generally when faced with a huge switch-case or if-else block the solution is to use polymorphism. Find the behavior that's changing and encapsulate it. I've had to deal with huge, ugly switch case code like this before and generally it's not that difficult to simplify. But oh so satisfying.

Solution 3 - C#

Believing this performance evaluation, the switch case is faster.

This is the conclusion:

> The results show that the switch statement is faster to execute than the if-else-if ladder. This is due to the compiler's ability to optimise the switch statement. In the case of the if-else-if ladder, the code must process each if statement in the order determined by the programmer. However, because each case within a switch statement does not rely on earlier cases, the compiler is able to re-order the testing in such a way as to provide the fastest execution.

Solution 4 - C#

Another thing to consider: is this really the bottleneck of your application? There are extremely rare cases when optimization of this sort is really required. Most of the time you can get way better speedups by rethinking your algorithms and data structures.

Solution 5 - C#

Switch is generally faster than a long list of ifs because the compiler can generate a jump table. The longer the list, the better a switch statement is over a series of if statements.

Solution 6 - C#

I'd say the switch is the way to go, it is both faster and better practice.

Here is a link that shows benchmark tests comparing the two.

Solution 7 - C#

Shouldn't be hard to test, create a function that switches or ifelse's between 5 numbers, throw a rand(1,5) into that function and loop that a few times while timing it.

Solution 8 - C#

switch usually gets translated into a lookup table by the compiler, if possible. So lookup of an arbitrary case is O(1), instead of actually doing a few case comparisons before finding the one you want.

So in many cases an if/else if chain will be slower. Depending on the frequency with which your cases are being hit that may make no difference, though.

Solution 9 - C#

Technically, they produce the exact same result so they should be optimizable in pretty much the same way. However, there are more chances that the compiler will optimize the switch case with a jump table than the ifs.

I'm talking about the general case here. For 5 entries, the average number of tests performed for the ifs should be less than 2.5, assuming you order the conditions by frequency. Hardly a bottleneck to write home about unless in a very tight loop.

Solution 10 - C#

Far more important than the performance benefits of switch (which are relatively slight, but worth noting) are the readability issues.

I for one find a switch statement extremely clear in intent and pure whitespace, compared to chains of ifs.

Solution 11 - C#

I'm not sure, but i believe the speed of one or the other changes depending on the programming language you're using.

I usually prefer to use switch. That way the code is simplear to read.

Solution 12 - C#

Short answer: Switch statement is quicker

The if statement you need two comparisons (when running your example code) on average to get to the correct clause.

The switch statement the average number of comparisons will be one regardless of how many different cases you have. The compiler/VM will have made a "lookup table" of possible options at compile time.

Can virtual machines optimize the if statement in a similar way if you run this code often?

Solution 13 - C#

Since the switch statement expresses the same intent as your if / else chain but in a more restricted, formal manner, your first guess should be that the compiler will be able to optimize it better, since it can draw more conclusions about the conditions placed on your code (i.e. only one state can possibly be true, the value being compared is a primitive type, etc.) This is a pretty safe general truth when you are comparing two similar language structures for runtime performance.

Solution 14 - C#

see http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.switch%28VS.71%29.aspx

switch statement basically a look up table it have options which are known and if statement is like boolean type. according to me switch and if-else are same but for logic switch can help more better. while if-else helps to understand in reading also.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIvan ProdanovView Question on Stackoverflow
Solution 1 - C#GuffaView Answer on Stackoverflow
Solution 2 - C#WedgeView Answer on Stackoverflow
Solution 3 - C#Michael KlementView Answer on Stackoverflow
Solution 4 - C#Vilx-View Answer on Stackoverflow
Solution 5 - C#StevenView Answer on Stackoverflow
Solution 6 - C#Shaun BohannonView Answer on Stackoverflow
Solution 7 - C#Ólafur WaageView Answer on Stackoverflow
Solution 8 - C#JoeyView Answer on Stackoverflow
Solution 9 - C#jfclavetteView Answer on Stackoverflow
Solution 10 - C#annakataView Answer on Stackoverflow
Solution 11 - C#user308693View Answer on Stackoverflow
Solution 12 - C#AnnaRView Answer on Stackoverflow
Solution 13 - C#mqpView Answer on Stackoverflow
Solution 14 - C#User42590View Answer on Stackoverflow