Updated on

A switch is faster than an if-else chain in C# only once it has enough cases for the compiler to build a jump table. With one or two cases, neither form wins consistently. From five cases on the same integer, the switch does less work, though our timings were too noisy to prove it faster.

We pick between them for readability first. An if-else chain is still the right tool when each condition tests something different, and on a short chain neither one is reliably faster.

We also fixed this article’s own benchmark. The earlier version of this benchmark threw every result away, which let the compiler delete most of the work it was meant to measure. The numbers below come from benchmarks that return their results.

To download the source code for this article, you can visit our GitHub repository.

Let’s dive in.

Understanding Control Flow Statements

Control flow statements are fundamental to any kind of programming as they allow us to dictate execution flow based on conditions or loops.

The if-else Statement

Firstly, the if-else statement allows us to build more complex and nuanced decision-making logic with the capability to evaluate equality and a range of other logical conditions. Let’s put one in a small ControlFlowExamples class:

public static class ControlFlowExamples
{
    public static string DescribeWithIfElse(int variable)
    {
        if (variable == 1)
        {
            return "First case";
        }
        else if (variable == 2)
        {
            return "Second case";
        }
        else
        {
            return "Default case";
        }
    }
}

The if-else statement evaluates the conditions specified in the if and else if clauses, executing the corresponding code block. Should these conditions not be satisfied, the code within the else block is executed.

While the if-else statement provides greater flexibility, it can become cumbersome with many discrete values of a single variable, and from about five of them it also does more work than a switch.

The switch Statement

The alternative is the switch statement that offers a streamlined method for dispatching execution to different parts of code based on the value of an expression.

It’s particularly efficient when comparing the same variable to multiple constants, offering a clean and efficient alternative to multiple if-else statements. We add the switch version to the same class:

public static string DescribeWithSwitch(int variable)
{
    switch (variable)
    {
        case 1:
            return "First case";
        case 2:
            return "Second case";
        default:
            return "Default case";
    }
}

The switch statement matches the variable’s value with one of the case clauses before executing the appropriate code block. The default code block executes if the value doesn’t match any of the cases.

This structure is cleaner and potentially faster for multiple comparisons, as the C# compiler can optimize switch statements in certain scenarios.

Moreover, with the introduction of C# 8.0, the switch statement is now augmented with switch expressions that offer a more concise syntax for scenarios requiring a return value based on a single condition. Here is the third method in our class:

public static string DescribeWithSwitchExpression(int variable) => variable switch
{
    1 => "First case",
    2 => "Second case",
    _ => "Default case",
};

This streamlines code and introduces pattern-matching enhancements that make switch expressions more powerful.

When Is switch Faster Than if-else?

A switch on one integer can be faster than the matching if-else chain once it has enough cases for the compiler to emit a jump table. In our tests, the jump table appears at five cases.

The reason is the shape of the machine code. An if-else chain compares the value with each constant in turn, so the fifth branch runs only after four failed comparisons. A switch with enough dense integer cases becomes one range check and one indexed jump, however many cases it has.

With one or two cases, there is nothing to gain. Both forms come down to a comparison or two, and our timings for them go either way.

The switch expression behaves like the switch statement here. On .NET 11, the JIT gave both the same instructions, only reordered, in our five-case test.

So speed only matters for long chains on a single value. For short chains, ranges, or conditions on several variables, we pick whichever reads better.

One-Condition Scenario

To evaluate performance, we will use the BenchmarkDotNet Nuget package.

We add it to a console project with dotnet add package BenchmarkDotNet and start the benchmarks from Program.cs:

using BenchmarkDotNet.Running;

BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args);

First, let’s define the SwitchVsIfElseBenchmarkTests class:

using BenchmarkDotNet.Attributes;

[InProcess]
public class SwitchVsIfElseBenchmarkTests
{
    private readonly int _iterations = 1000;
    private int[] _inputData = [];

    [GlobalSetup]
    public void Setup()
    {
        _inputData = new int[_iterations];

        for (int i = 0; i < _iterations; i++)
        {
            _inputData[i] = i % 10;
        }
    }
}

We define the SwitchVsIfElseBenchmarkTests class with two private fields and a Setup() method. BenchmarkDotNet runs a method marked with the [GlobalSetup] attribute before it measures anything, so building the input there keeps that work out of our timings.

The _iterations field is an integer representing the number of test iterations to be performed.

The _inputData field is an array of integers populated with numbers 0 through 9 in a repeating sequence.

Every benchmark method in this class returns an int. Each one adds its result to a running sum and returns the total. Without that, the compiler sees that nobody reads result and removes the work we want to measure. The BenchmarkDotNet good-practices guide says it in one line: “You should also use the result of calculation.”

The earlier version of this benchmark skipped that step. On .NET 11, the JIT compiled its five-case switch loop down to an array bounds check, with no comparison of the value left in it, which is why the switch timings looked flat however many cases we added.

We run all the benchmarks with dotnet run -c Release -- --filter "*".

Now, let’s define test methods that will test the performance of our statements with only one condition:

[Benchmark]
public int IfElseWithOneCondition()
{
    int result;
    var sum = 0;

    for (int i = 0; i < _iterations; i++)
    {
        if (_inputData[i] == 1)
        {
            result = 1;
        }
        else
        {
            result = -1;
        }

        sum += result;
    }

    return sum;
}

[Benchmark]
public int SwitchWithOneCase()
{
    int result;
    var sum = 0;

    for (int i = 0; i < _iterations; i++)
    {
        switch (_inputData[i])
        {
            case 1:
                result = 1;
                break;
            default:
                result = -1;
                break;
        }

        sum += result;
    }

    return sum;
}

[Benchmark]
public int SwitchExpressionWithOneCase()
{
    int result;
    var sum = 0;

    for (int i = 0; i < _iterations; i++)
    {
        result = _inputData[i] switch
        {
            1 => 1,
            _ => -1
        };

        sum += result;
    }

    return sum;
}

Here, we define three methods and mark them with Benchmark attributes.

Our IfElseWithOneCondition() method measures the performance of the if-else statement with a single condition. Within a loop, it checks if each element in the _inputData array equals 1, sets result accordingly and adds it to sum.

Similarly, we define the SwitchWithOneCase() method using the switch statement and the SwitchExpressionWithOneCase() method using the switch expression.

Now, let’s compare the execution times of each method:

| Method                      | Mean     | Error    | StdDev   |
|---------------------------- |---------:|---------:|---------:|
| SwitchWithOneCase           | 640.2 ns | 12.21 ns | 14.53 ns |
| SwitchExpressionWithOneCase | 657.9 ns | 12.88 ns | 20.43 ns |
| IfElseWithOneCondition      | 703.4 ns | 14.08 ns | 30.60 ns |

The exact times change from machine to machine and from run to run, so we compare the rows with each other. As we can see, with one condition the if-else method is slightly slower in this run, though the JIT gives all three methods the same machine code.

The switch expression carries no extra cost either. The JIT turns it into the same machine code as the switch statement, so any gap between those two rows is measurement noise.

Two-Condition Scenario

Now, let’s add the next methods with two conditions:

[Benchmark]
public int IfElseWithTwoConditions()
{
    int result;
    var sum = 0;

    for (int i = 0; i < _iterations; i++)
    {
        if (_inputData[i] == 1)
        {
            result = 1;
        }
        else if (_inputData[i] == 2)
        {
            result = 2;
        }
        else
        {
            result = -1;
        }

        sum += result;
    }

    return sum;
}

[Benchmark]
public int SwitchWithTwoCases()
{
    int result;
    var sum = 0;

    for (int i = 0; i < _iterations; i++)
    {
        switch (_inputData[i])
        {
            case 1:
                result = 1;
                break;
            case 2:
                result = 2;
                break;
            default:
                result = -1;
                break;
        }

        sum += result;
    }

    return sum;
}

[Benchmark]
public int SwitchExpressionWithTwoCases()
{
    int result;
    var sum = 0;

    for (int i = 0; i < _iterations; i++)
    {
        result = _inputData[i] switch
        {
            1 => 1,
            2 => 2,
            _ => -1
        };

        sum += result;
    }

    return sum;
}

The testing logic is the same as in our previous tests.

The only difference is an additional else-if statement in our IfElseWithTwoConditions() method and an additional case statement in our SwitchWithTwoCases() and SwitchExpressionWithTwoCases() methods.

Now, let’s see how it affects the results:

| Method                       | Mean       | Error    | StdDev   |
|----------------------------- |-----------:|---------:|---------:|
| IfElseWithTwoConditions      |   877.1 ns | 17.18 ns | 22.34 ns |
| SwitchExpressionWithTwoCases |   899.1 ns | 17.91 ns | 28.92 ns |
| SwitchWithTwoCases           | 1,266.4 ns | 25.35 ns | 27.12 ns |

As we can see, with two conditions the if-else chain and the switch expression stay within the noise of each other. The switch statement is the slow one in this run, at about 1.4 times as long, but the JIT gave both switch forms the same machine code, so the gap between them is run-to-run variation, not the code.

Five-Condition and Ten-Condition Scenarios

By now, the trend in our testing methodology is clear.

Therefore, examples for five and ten conditions can be found in the sample solution. In short, the only difference compared to our previous tests is the increased number of conditions for each statement.

Now, let’s see how five conditions affect our performance:

| Method                        | Mean       | Error    | StdDev   |
|------------------------------ |-----------:|---------:|---------:|
| SwitchExpressionWithFiveCases | 1,154.4 ns | 22.45 ns | 30.72 ns |
| SwitchWithFiveCases           | 1,491.1 ns | 21.04 ns | 19.68 ns |
| IfElseWithFiveConditions      | 1,540.5 ns | 18.65 ns | 15.58 ns |

Now the if-else chain is the slowest row, at about 1.03 times the switch statement and 1.33 times the switch expression, but both gaps are smaller than the 1.4 times gap between identical code with two conditions.

Lastly, let’s see how ten conditions affect the performance:

| Method                       | Mean       | Error    | StdDev   |
|----------------------------- |-----------:|---------:|---------:|
| SwitchWithTenCases           | 1,821.1 ns | 35.68 ns | 53.40 ns |
| SwitchExpressionWithTenCases | 1,902.7 ns | 37.96 ns | 76.69 ns |
| IfElseWithTenConditions      | 2,141.4 ns | 42.36 ns | 69.61 ns |

The switch forms are again the faster rows with ten conditions, by less than the noise we saw with two. In this run all three rows grew.

To sum up, a switch does less work on a long chain of constant checks against one value. With one or two conditions, we choose the form that reads better.

Why Is switch Faster Than if-else With Many Cases?

Because the C# compiler and the JIT turn a switch into a lookup, while an if-else chain stays a list of tests.

For dense integer cases, the C# compiler emits the IL switch instruction, which is a jump table indexed by the value. Our five-case method subtracts 1 from the input and hands the result to a single switch instruction with five targets. The JIT then turns that table into one bounds check and an indirect jmp.

The if-else chain gets no such treatment. On .NET 11, the JIT keeps our five-condition chain as five cmp and je pairs, one per branch, so the value 5 pays for four failed comparisons before it matches.

Strings follow a different route. A string cannot index a table, so the compiler first switches on the string’s length, then checks one character, and only then calls the full string comparison, once.

To visualize it, let’s have a look at an example in a new SwitchLoweringExamples class:

public static class SwitchLoweringExamples
{
    public static string AnimalSounds(string animal)
    {
        switch (animal)
        {
            case "dog":
                return "Woof";
            case "cat":
                return "Meow";
            default:
                return "<silence>";
        }
    }
}

Here, we define the AnimalSounds() method that accepts a string parameter. In the method body, we have a switch statement that based on the parameter returns a string value.

Now, let’s see what a decompiler such as ILSpy shows for the compiled method:

public static string AnimalSounds(string animal)
{
    if (!(animal == "dog"))
    {
        if (animal == "cat")
        {
            return "Meow";
        }
        return "<silence>";
    }
    return "Woof";
}

As we can see, the switch statement is converted to a set of nested if statements.

It gets even more interesting if we add more cases:

public static string AnimalSoundsWithMoreCases(string animal)
{
    switch (animal)
    {
        case "dog":
            return "Woof";
        case "cat":
            return "Meow";
        case "horse":
            return "Neigh";
        case "bird":
            return "Chirp";
        case "fish":
            return "<Bubbles sound>";
        case "mouse":
            return "Peep";
        case "oyster":
            return "...";
        default:
            return "<silence>";
    }
}

Now, the switch statement has seven cases plus the default branch.

This time, ILSpy folds the compiled code back into a switch, so we read the IL instead. Written back out as C#, the IL does this:

public static string AnimalSoundsWithMoreCases(string animal)
{
    if (animal != null)
    {
        switch (animal.Length)
        {
            case 5:
            {
                char c = animal[0];
                if (c != 'h')
                {
                    if (c == 'm' && animal == "mouse")
                    {
                        return "Peep";
                    }
                }
                else if (animal == "horse")
                {
                    return "Neigh";
                }
                break;
            }
            case 3:
            {
                char c = animal[0];
                if (c != 'c')
                {
                    if (c == 'd' && animal == "dog")
                    {
                        return "Woof";
                    }
                }
                else if (animal == "cat")
                {
                    return "Meow";
                }
                break;
            }
            case 4:
            {
                char c = animal[0];
                if (c != 'b')
                {
                    if (c == 'f' && animal == "fish")
                    {
                        return "<Bubbles sound>";
                    }
                }
                else if (animal == "bird")
                {
                    return "Chirp";
                }
                break;
            }
            case 6:
                if (!(animal == "oyster"))
                {
                    break;
                }
                return "...";
        }
    }
    return "<silence>";
}

In this case, the compiler restructures the code to minimize expensive operations, like full string comparisons, by performing quicker, more efficient checks, like length and character comparisons.

This kind of optimization demonstrates the compiler’s role in code translation and also in enhancing its execution efficiency without altering its semantic meaning.

It is also important to note that compiler optimization will likely differ between .NET versions, and some will bring greater performance gains than others, so it pays to benchmark the same method across .NET versions.

Is Pattern Matching Faster Than if-else?

Now, we know how the work differs between the if-else statement and the switch statement and expression.

However, as we mentioned before the switch expression can be enhanced with pattern-matching, let’s see how it affects the performance of our code in comparison to complex if-else statements.

First, let’s define a few helping classes:

public class Circle
{
    public int Radius { get; set; }
}

public class Line
{
    public int Length { get; set; }
}

public class Rectangle
{
    public int Width { get; set; }
    public int Height { get; set; }
}

Now, let’s define the PatternMatchingVsComplexIfElseBenchmarkTests class:

using BenchmarkDotNet.Attributes;

[InProcess]
public class PatternMatchingVsComplexIfElseBenchmarkTests
{
    private readonly object[] _shapes =
    [
        new Circle { Radius = 12 },
        new Circle { Radius = 4 },
        new Rectangle { Width = 4, Height = 4 },
        new Rectangle { Width = 4, Height = 10 },
        new Line { Length = 10 },
    ];

    [Benchmark]
    public int IfElseWithComplexConditions()
    {
        var totalLength = 0;

        foreach (object shape in _shapes)
        {
            totalLength += ClassifyShapeWithIfElse(shape).Length;
        }

        return totalLength;
    }

    [Benchmark]
    public int SwitchExpressionWithPatternMatching()
    {
        var totalLength = 0;

        foreach (object shape in _shapes)
        {
            totalLength += ClassifyShapeWithPatternMatching(shape).Length;
        }

        return totalLength;
    }

    private static string ClassifyShapeWithIfElse(object shape)
    {
        if (shape is Circle circle)
        {
            if (circle.Radius > 10)
            {
                return "Large Circle";
            }

            return "Circle";
        }

        if (shape is Rectangle rectangle)
        {
            if (rectangle.Height == rectangle.Width)
            {
                return "Square";
            }

            return "Rectangle";
        }

        return "Unknown Shape";
    }

    private static string ClassifyShapeWithPatternMatching(object shape) =>
        shape switch
        {
            Circle { Radius: > 10 } => "Large Circle",
            Circle => "Circle",
            Rectangle { Width: var w, Height: var h } when w == h => "Square",
            Rectangle => "Rectangle",
            _ => "Unknown Shape"
        };
}

Here, we define the _shapes field, an array of objects that we initialize with instances of the Circle, Rectangle and Line classes.

Then, we create the IfElseWithComplexConditions() method that iterates over the _shapes array, calling the ClassifyShapeWithIfElse() method to categorize each shape with if-else statements and return a string label. We add up the label lengths and return the total, so the work cannot be optimized away.

Similarly, the SwitchExpressionWithPatternMatching() and ClassifyShapeWithPatternMatching() methods do the same task, but they classify each shape with a switch expression and property patterns such as Circle { Radius: > 10 }.

The if-else version uses declaration patterns (shape is Circle circle), which is how current C# code checks a type and casts it in one step.

Now, let’s check our results:

| Method                              | Mean     | Error    | StdDev   |
|------------------------------------ |---------:|---------:|---------:|
| IfElseWithComplexConditions         | 15.79 ns | 0.338 ns | 0.416 ns |
| SwitchExpressionWithPatternMatching | 21.76 ns | 0.465 ns | 0.636 ns |

This time, the if-else row is the lower one. The switch expression takes about 1.4 times as long in our run, about the size of the noise we saw with two conditions.

Our earlier benchmark reported the opposite, with the switch expression almost two times faster. Its methods discarded the shape names too.

We use pattern matching because it reads better. Whether it is faster depends on the code it replaces, so we measure our own case before choosing it for speed.

Common Mistakes and Best Practices

While both statements are indispensable in C# programming, incorrect usage can cause unnecessary complexity, performance issues, and difficulty maintaining or debugging code.

Understanding common mistakes and adhering to best practices that can significantly improve code efficiency and readability is important.

Overusing if-else for Simple Value Checks

Firstly, a long if-else chain that checks a single variable against many constants does more work than a switch statement and is harder to read.

Therefore, we should use the switch statements for these conditions and the if-else statements for more complex conditions involving multiple variables or ranges.

When several values should give the same result, we can combine several switch cases into one result instead of repeating the branch.

Avoid Excessive Nesting

Next, deeply nested if-else statements can make our code harder to read and maintain.

For this reason, we should consider refactoring deeply nested structures into separate methods or using pattern matching to simplify the logic.

Leverage Pattern Matching with switch Expressions

Lastly, in C# 8 and later, switch expressions offer a more concise syntax for some scenarios. In general, it allows for pattern matching and improves code readability.

A switch expression is not reliably faster than a switch statement, though. For our five integer cases, the JIT produced the same instructions for both, in a different order, so we choose between them for readability.

Should I Use switch or if-else?

Most of the choice comes down to the shape of the condition. This table sums up what our measurements and the compiled code show:

SituationUseWhy
One variable against five or more constantsswitch statement or switch expressionThe compiler builds a jump table; our run leaned this way but stayed inside its noise
One variable against one or two constantsEither, whichever reads betterNo consistent winner in our benchmarks
Conditions that each test something differentif-elseEach condition can test anything; a switch tests one expression against its patterns
Classifying objects by type and propertyswitch expression with patterns, for readabilityNot faster than if-else in our run
Many string constantsswitchThe compiler checks length and one character before a single full string comparison

Speed only decides the first row. Everywhere else, we keep the version that is easier to read.

Conclusion

In conclusion, the compiled code shows that a switch does less work than an if-else chain once it checks one value against about five constants or more, though our timings could not separate the two from noise. With one or two conditions, neither one wins consistently.

We have also seen how the compiler turns a switch into a jump table, and how a benchmark that throws its results away lets the JIT delete the very code it should measure.

So the right control flow statement depends on our needs and the shape of the code, and readability decides most of the time.

Tested with .NET 11.0.0 (SDK 11.0.100) and BenchmarkDotNet 0.15.8.