header image
 

Newsflash: Enum.HasFlag is slow

I finally managed to repair my Visual Studio’s profiler – turns out the profiling driver was corrupted (wrong image size in PE header, only 2 bytes). Anyway, I launched Gwen.Net’s SFML sample and quickly browsed through the profiler output. One peculiar thing caught my eye: Enum.HasFlag method calls amounted to around 5% samples inclusive. What?! Sure that can’t be right? Flag testing is extensively used in control positioning and layout code, but 5%? I’ve replaced all occurrences with manual bit testing and fired up Net Reflector:

public bool HasFlag(Enum flag)
{
    if (!base.GetType().IsEquivalentTo(flag.GetType()))
    {
        throw new ArgumentException(Environment.GetResourceString("Argument_EnumTypeDoesNotMatch", new object[] { flag.GetType(), base.GetType() }));
    }
    ulong num = ToUInt64(flag.GetValue());
    return ((ToUInt64(this.GetValue()) & num) == num);
}

Wow. Type checking, boxing and conversions. I’ve used HasFlag mainly for it’s verbosity, but I guess I’ll stop now.

~ by omeg on October 11, 2011.

C#, code, performance

Leave a Reply