Skip to content

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

@rameel

Description

@rameel

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.

Metadata

Metadata

Assignees

Labels

Area-CompilersCode Gen QualityRoom for improvement in the quality of the compiler's generated codeOngoing-Quality-Candidatehelp wantedThe issue is "up for grabs" - add a comment if you are interested in working on it
No fields configured for Feature.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions