DEV Community

Cover image for If-Else vs. Switch Case: Performance Comparison in .NET 9
Apurv Upadhyay
Apurv Upadhyay

Posted on

If-Else vs. Switch Case: Performance Comparison in .NET 9

In .NET applications, choosing the right control structure can have a significant impact on performance, especially when working with a large number of conditions. Both If-Else and Switch Case serve similar purposes, but they are optimized for different scenarios. Here’s an in-depth comparison with a .NET 9 performance benchmark to understand the differences!

Image description
If-Else vs. Switch Case: Key Differences

• If-Else is better for complex conditions involving ranges, multiple variables, or compound logical expressions.

• Switch Case shines in cases where you are matching a single variable against constant values. .NET’s switch is optimized for these scenarios, especially in .NET 9, where it benefits from specific performance improvements.

Benchmarking in .NET 9

To objectively compare If-Else and Switch Case, I set up a benchmark using BenchmarkDotNet in .NET 9. The code below tests each structure’s efficiency when handling 100 conditions, simulating a high-load scenario.

using System;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;

[MemoryDiagnoser] 
[SimpleJob(RuntimeMoniker.Net90, invocationCount: 1000000, iterationCount: 50)]
public class SwitchVsIfElseBenchmark
{
    private int number;

    [GlobalSetup]
    public void Setup()
    {
        Random random = new Random();
        number = random.Next(1, 101); 
    }

    [Benchmark]
    public int IfElse()
    {
        if (number == 1) return 1;
        else if (number == 2) return 2;
        else if (number == 3) return 3;
        else if (number == 4) return 4;
        else if (number == 5) return 5;
        else if (number == 6) return 6;
        else if (number == 7) return 7;
        else if (number == 8) return 8;
        else if (number == 9) return 9;
        else if (number == 10) return 10;
        // Add more conditions up to 100 for heavy load
        else if (number == 100) return 100;
        return 0; 
    }

    [Benchmark]
    public int Switch()
    {
        switch (number)
        {
            case 1: return 1;
            case 2: return 2;
            case 3: return 3;
            case 4: return 4;
            case 5: return 5;
            case 6: return 6;
            case 7: return 7;
            case 8: return 8;
            case 9: return 9;
            case 10: return 10;
            // Add more cases up to 100 for heavy load
            case 100: return 100;
            default: return 0; 
        }
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        var config = DefaultConfig.Instance
            .WithOptions(ConfigOptions.DisableOptimizationsValidator); 
        BenchmarkRunner.Run<SwitchVsIfElseBenchmark>(config);
    }
}
Enter fullscreen mode Exit fullscreen mode

Benchmark Results Summary

Image description

Results Analysis

• Switch Case proved 4–5 times faster than If-Else in this scenario.

• The reduced latency for switch in .NET 9 makes it ideal for scenarios where a large number of single-value comparisons are required.

• Memory Usage: Both methods have minimal memory footprint, but switch is more optimized for high-frequency operations.

When to Use Each Structure

Use If-Else When:

• Conditions are complex or involve multiple variables.

• You’re checking ranges or compound logical expressions (e.g., if (x > 10 && y < 20)).

• The number of conditions is small, and readability is more important than slight performance gains.

Use Switch Case When:

• Matching a single variable against multiple constant values.

• Handling large sets of discrete options, like enums or integer values.

• Performance is critical, and the conditions are straightforward.

Key Takeaways

• If-Else is flexible and ideal for complex conditions, but can be slower for large, single-variable comparisons.

• Switch Case is highly optimized in .NET 9, making it the preferred choice for high-frequency scenarios with multiple discrete options.

• For performance-sensitive applications, use switch whenever feasible, especially in high-throughput systems.

Real-World Application

Consider this benchmark and tips when optimizing critical sections of your code, such as handling user input conditions, API request processing, or business rule engines.

Switch to switch if you’re looking for a performance boost in scenarios with single-value matching!

❤️ Share Your Thoughts!

Feel free to repost ♻️ if you found this helpful. For more great content like this follow 🛠 Apurv Upadhyay. Until next time, happy coding! 🚀

DotNet9 #SwitchVsIfElse #PerformanceOptimization #BackendDevelopment #CodingBestPractices

Top comments (2)

Collapse
 
moopet profile image
Ben Sinclair

These differences aren't significant for most cases. 4-5 times slower sounds a lot until you realise you're talking about nanoseconds. Unless this is code run in a loop billions of times, it's not going to matter, and if you're doing that, you probably aren't using dot net!

Consider this benchmark and tips when optimizing critical sections of your code, such as handling user input conditions, API request processing, or business rule engines.

All those examples have much more significant bottlenecks - API requests depend on network or IPC traffic, user input relies on... users... and so on. The real-world examples I can think of where this matters is things like game-loop physics processing, real-time DAW processing, low-level drivers, that sort of thing.

I think that readability is much more important. There are people who don't like to ever use switch and those who don't ever like to use else and I'm kind of inclined to agree with both. If your code needs complex conditions like this then I'd look at refactoring it in the first instance rather than choosing which option is infinitesimally faster.

Collapse
 
apurvupadhyay profile image
Apurv Upadhyay

Absolutely agree! The performance difference between if-else and switch is often negligible in most real-world applications, especially when we’re talking about nanoseconds. In a typical scenario, you’d rarely encounter a case where this micro-optimization is the primary bottleneck.

Context matters: As you rightly pointed out, situations involving network traffic (like API requests) or user interactions have vastly larger delays that make this difference trivial. The only cases where this would truly matter are those with high-frequency, time-sensitive operations—like game loops, real-time audio processing in DAWs, or certain low-level drivers. For the average developer, readability and maintainability will have a far more significant impact than shaving off nanoseconds.

Readability and Code Quality: Another excellent point! Code that relies on clear, understandable logic is easier to maintain and debug, especially for complex conditions. Often, if the condition structure is becoming complicated, it’s worth refactoring to break down the logic instead of choosing between if-else and switch for marginal speed gains. Code clarity tends to outweigh tiny performance boosts in scenarios that aren’t incredibly performance-sensitive.

In short, unless this code is being used in a high-frequency loop or highly optimized system, I’d prioritize readability and clean structure over micro-optimizations like this.