What is it that makes Enum.HasFlag so slow?

Does anyone know the internals of Enum.HasFlag and why it is so slow?

The actual check is just a simple bit check in Enum.HasFlag – it’s not the problem here. That being said, it is slower than your own bit check…

There are a couple of reasons for this slowdown:

First, Enum.HasFlag does an explicit check to make sure that the type of the enum and the type of the flag are both the same type, and from the same Enum. There is some cost in this check.

Secondly, there is an unfortunate box and unbox of the value during a conversion to UInt64 that occurs inside of HasFlag. This is, I believe, due to the requirement that Enum.HasFlag work with all enums, regardless of the underlying storage type.

That being said, there is a huge advantage to Enum.HasFlag – it’s reliable, clean, and makes the code very obvious and expressive. For the most part, I feel that this makes it worth the cost – but if you’re using this in a very performance critical loop, it may be worth doing your own check.

Leave a Comment