How to Compare Flags in C#?

前端 未结 11 1752
我寻月下人不归
我寻月下人不归 2020-11-27 04:03

I have a flag enum below.

[Flags]
public enum FlagTest
{
    None = 0x0,
    Flag1 = 0x1,
    Flag2 = 0x2,
    Flag3 = 0x4
}

I cannot make

11条回答
  •  难免孤独
    2020-11-27 04:32

    @phil-devaney

    Note that except in the simplest of cases, the Enum.HasFlag carries a heavy performance penalty in comparison to writing out the code manually. Consider the following code:

    [Flags]
    public enum TestFlags
    {
        One = 1,
        Two = 2,
        Three = 4,
        Four = 8,
        Five = 16,
        Six = 32,
        Seven = 64,
        Eight = 128,
        Nine = 256,
        Ten = 512
    }
    
    
    class Program
    {
        static void Main(string[] args)
        {
            TestFlags f = TestFlags.Five; /* or any other enum */
            bool result = false;
    
            Stopwatch s = Stopwatch.StartNew();
            for (int i = 0; i < 10000000; i++)
            {
                result |= f.HasFlag(TestFlags.Three);
            }
            s.Stop();
            Console.WriteLine(s.ElapsedMilliseconds); // *4793 ms*
    
            s.Restart();
            for (int i = 0; i < 10000000; i++)
            {
                result |= (f & TestFlags.Three) != 0;
            }
            s.Stop();
            Console.WriteLine(s.ElapsedMilliseconds); // *27 ms*        
    
            Console.ReadLine();
        }
    }
    

    Over 10 million iterations, the HasFlags extension method takes a whopping 4793 ms, compared to the 27 ms for the standard bitwise implementation.

提交回复
热议问题