Enum.HasFlag(Enum e) is a dynamic check and pretty expensive at that. It causes boxing of the argument, performs comparison of the runtime types of "this" and the operand, and so on.
However, I keep seeing the common mistake to use HasFlag in trivial cases where types of "this" and the operand match statically and thus a simple & check would be much cheaper.
I believe it would be for the common good to lower trivial HasFlag calls into (this & operand) != 0
Pedantically speaking such optimization is disallowed, since we cannot be sure about implementation of Enum.HasFlag. However, what are the chances that it will ever be different in the trivial case?
Related to https://github.com/dotnet/corefx/issues/693
Perhaps this should be done by the JIT compiler?
@tmat There's already an issue for that: https://github.com/dotnet/coreclr/issues/5626.
Also, HasFlag can only be considered a "mistake" because of its performance, otherwise, I'd say it's a readability win
@tmat - handling this in JIT(s) would be good. There are some advantages in the lowering-time optimization too. Reducing the strength of the expression early may enable other optimizations both in the C# backend and in the JIT.
@VSadov I think the correct implementation would be (this & operand) == operand apart from that this might be the easiest way to fix Enum.HasFlag, god suggestion.
Should this be closed now that the JIT optimizes Enum.HasFlag?
https://github.com/dotnet/coreclr/issues/5626
https://github.com/dotnet/coreclr/pull/13748
This may be addressed by the System.Enum constraint (candidate feature for C# 7.3): https://github.com/dotnet/csharplang/issues/104
Most helpful comment
Perhaps this should be done by the JIT compiler?