[c#] Is "else if" faster than "switch() case"?

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?

This question is related to c# performance if-statement switch-statement

The answer is


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

There are various links such as (http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx) that show benchmark tests comparing the two.


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.


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.


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.


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.


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.


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.


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.


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.


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?


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.


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.


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.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to performance

Why is 2 * (i * i) faster than 2 * i * i in Java? What is the difference between spark.sql.shuffle.partitions and spark.default.parallelism? How to check if a key exists in Json Object and get its value Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly? Most efficient way to map function over numpy array The most efficient way to remove first N elements in a list? Fastest way to get the first n elements of a List into an Array Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3? pandas loc vs. iloc vs. at vs. iat? Android Recyclerview vs ListView with Viewholder

Examples related to if-statement

How to use *ngIf else? SQL Server IF EXISTS THEN 1 ELSE 2 What is a good practice to check if an environmental variable exists or not? Using OR operator in a jquery if statement R multiple conditions in if statement Syntax for an If statement using a boolean How to have multiple conditions for one if statement in python Ifelse statement in R with multiple conditions If strings starts with in PowerShell Multiple conditions in an IF statement in Excel VBA

Examples related to switch-statement

Switch in Laravel 5 - Blade Switch case: can I use a range instead of a one number SQL use CASE statement in WHERE IN clause SSRS Conditional Formatting Switch or IIF Switch statement equivalent in Windows batch file OR operator in switch-case? Regarding Java switch statements - using return and omitting breaks in each case Using two values for one switch case statement C# how to use enum with switch Switch statement multiple cases in JavaScript