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