NuGet / Home

Repo for NuGet Client issues
Other
1.5k stars 252 forks source link

Avoid invoking Enum.HasFlag(Enum) Method in .NET Framework code paths. #12740

Open kartheekp-ms opened 1 year ago

kartheekp-ms commented 1 year ago

Avoid the following code in .NET Framework code paths because there are 2 boxing operations in flags.HasFlag(MyFlags.Bit1) method call resulting in unnecessary heap allocations.

[Flags]
enum MyFlags
{
    None = 0,
    Bit1 = 1,
    Bit2 = 2,
    All = Bit1 | Bit2
}

bool HasBit1(MyFlags flags)
{
    return flags.HasFlag(MyFlags.Bit1);
}

Prefer the following implementation as there are no heap allocations required.

[Flags]
enum MyFlags
{
    None = 0,
    Bit1 = 1,
    Bit2 = 2,
    All = Bit1 | Bit2
}

bool HasBit1(MyFlags flags)
{
    return (flags & MyFlags.Bit1) == MyFlags.Bit1;
}

There are several occurrences of Enum.HasFlag invocation in NuGet Client repo https://github.com/search?q=repo%3ANuGet%2FNuGet.Client%20HasFlag&type=code.

cc @drewnoakes - Thanks for sharing this tip.

drewnoakes commented 1 year ago

I suggest you also configure the banned API analyser to flag usages of this method.

drewnoakes commented 1 year ago

You could also write your own HasFlag extension methods for specific enums to keep the same call-site code and avoid the allocations.