dotnet/roslyn

Suboptimal codegen for `is` pattern compared to .NET 6/7

開放

#80,052 建立於 2025年8月26日

 (3 則留言) (1 個反應) (1 位負責人)C# (4,257 個分叉)batch import
Area-CompilersCode Gen QualityOngoing-Quality-Candidatehelp wanted

倉庫指標

星標
 (20,414 顆星)
PR 合併指標
 (平均合併 6天 17小時) (30 天內合併 256 個 PR)

描述

A simple method with a pattern match is generates less efficient code starting from .NET 8 compared to .NET 6/7.

Repro: godbolt

public static bool HasLeadingSlash(ReadOnlySpan<char> path)
{
    if (path.Length > 0 && path[0] is '/' or '\\')
        return true;

    return false;
}

.NET 8,9,10 (IL size: 49 bytes):

public static bool HasLeadingSlash(ReadOnlySpan<char> path)
{
    bool flag = path.Length > 0;
    if (flag)
    {
        char c = path[0];
        bool flag2 = ((c == '/' || c == '\\') ? true : false);
        flag = flag2;
    }

    if (flag)
    {
        return true;
    }

    return false;
}

.NET 6,7 (IL size: 34 bytes):

public static bool HasLeadingSlash(ReadOnlySpan<char> path)
{
    if (path.Length > 0)
    {
        char c = path[0];
        if (c == '/' || c == '\\')
        {
            return true;
        }
    }
    return false;
}

Roslyn now introduces unnecessary temporary bool variables and extra conditional branches. The JIT is unable to untangle this pattern, resulting in larger, slower code.

貢獻者指南