dotnet/roslyn

Suboptimal code for matching nullable value to constant pattern

开放

#42,912 创建于 2020年3月30日

 (1 条评论) (0 个反应) (0 位负责人)C# (4,257 个派生)batch import
Area-CompilersCode Gen QualityFeature - Pattern MatchingFeature Requesthelp wanted

仓库指标

星标
 (20,414 个星标)
PR 合并指标
 (平均合并 6天 17小时) (30 天内合并 256 个 PR)

描述

See https://sharplab.io/#v2:EYLgZgpghgLgrgJwgZwLQAdYwggdsgZgB8ABARgDYACEgJhrIHYBYAKAG82ruaCHrgAe0EAbKgElkAQQDG8KCIAUAS1wwA/FQAeASioBeAHzaqy5FTIBuKlx4k+5AcLGSAolvQQ5EACYq1mroGxloG+haWbAC+bGxAA=

This issue is extracted from https://github.com/dotnet/roslyn/issues/31494

For source

static class Program
{
    public static bool IsActual(int? x) => x is 1; 
    public static bool IsExpected(int? x) => x == 1;
}

The generated code is

internal static class Program
{
    public static bool IsActual(int? x)
    {
        if (x.HasValue)
        {
            return x.GetValueOrDefault() == 1;
        }
        return false;
    }

    public static bool IsExpected(int? x)
    {
        int? num = x;
        int num2 = 1;
        return (num.GetValueOrDefault() == num2) & num.HasValue;
    }
}

The point is that we optimized == to avoid control-flow. We should do the same for the pattern-matching operations.

贡献者指南