General Performance Tip: Choosing Between Conditional Statements – If, Switch, and Switch Expression Performance in C#

Do you prefer coding with conditional if statements or using a switch statement or expression? Do you know which is the most performant? A typical conditional if statement might look like this:

public static string GetData(DataType input)
{
    var result = string.Empty;

    if (input == DataType.CreditCard)
    {
        result = input.GetDescription();
    }
    else if (input == DataType.Currency)
    {
        result = input.GetDescription();
    }
    else if (input == DataType.Custom)
    {
        result = input.GetDescription();
    }

    return result;
}

.NET code analyzers will suggest changing the code above to a switch statement, as shown in this example:

public static string GetData(DataType input)
{
    var result = string.Empty;

    switch (input)
    {
        case DataType.CreditCard:
            result = input.GetDescription();
            break;
        case DataType.Currency:
            result = input.GetDescription();
            break;
        case DataType.Custom:
            result = input.GetDescription();
            break;
        default:
            break;
    }

    return result;
}

Starting with C# 8, analyzers will recommend converting a switch statement to a switch expression, as shown below:

public static string GetData(DataType input)
{
    var result = input switch
    {
        DataType.CreditCard => input.GetDescription(),
        DataType.Currency => input.GetDescription(),
        DataType.Custom => input.GetDescription(),
        _ => "UNKOWN"
    };

    return result;
}

Using a switch expression is more readable and requires less code. Now, let’s examine the performance.

Benchmark Results

In these results, all three methods exhibit similar performance, each allocating 24 bytes in memory.

My recommendation is to use a switch expression.
When I setup the code analysis in my EditorConfig it looks like this:
dotnet_diagnostic.IDE0066.severity = warning
csharp_style_prefer_switch_expression = true:warning

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave

© The information in this article is copywritten and cannot be preproduced in any way without express permission from David McCarter.


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.