Skip to content

Instantly share code, notes, and snippets.

@marbel82
Last active August 18, 2022 13:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marbel82/558891ccc6f6cc13321e3bb501e7cf2d to your computer and use it in GitHub Desktop.
Save marbel82/558891ccc6f6cc13321e3bb501e7cf2d to your computer and use it in GitHub Desktop.
Simple test of Enum.GetValues() with casting type and without

Simple test of Enum.GetValues() with casting type and without

It was some time ago. I wondered why some people explicitly cast the type of value returned by the Enum.GetValues() function. I did some tests.

Unfortunately, the functions are so short that StopWatch is inaccurate. Therefore, I call them in a large loop and then divide the time by the number of repetitions.

public class C {
    enum Sizes
	{
	    Small,
    	Medium,
    	Large
	}
    void Fun1()
    {
        foreach (Sizes s in Enum.GetValues(typeof(Sizes)))
        {}
    }
    void Fun2()
    {
        foreach (Sizes s in (Sizes[])Enum.GetValues(typeof(Sizes)))
        {}
    }
}

static void Main(string[] args)
{
    C c = new C();
    int count = 1000000;
    do
    {
        Stopwatch watch = Stopwatch.StartNew();
        for (int i = 0; i < count; i++)
        { 
            c.Fun1();
            //c.Fun2();
        }
        watch.Stop();

        Console.WriteLine("Duration: {0:0.000} us",
                          watch.Elapsed.TotalMilliseconds * 1000 / count);
        
    } while (true);
}

I'm waiting a moment, until the results stabilize and then average the latter. Then I take the second function and run again. I've also done, a test of more values like. I don't remember what they were, but let's assume that 10, 100 and 1000.

The results are as follows:

Method Enum elements Mean Faster than Fun1
Fun1 3 1.515 us
Fun2 3 1.019 us 1.49x
Fun1 10 3.998 us
Fun2 10 2.777 us 1.44x
Fun1 100 35.581 us
Fun2 100 21.056 us 1.69x
Fun1 1000 358.217 us
Fun2 1000 214.417 us 1.67x
Mean: 1.5725x

That's why I wrote in a comment on stackoverflow.com that "my code run 1,6 times faster".

I know that this test was not perfect.

The continuation of this story will be... here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment