In the code below, I get 10 seconds with a custom constructor
This is not a code that takes 10 seconds unless you have a very old machine. Tells us what you did wrong, you run an unoptimized Debug build or run an application with an attached debugger. The type of scenario in which the optimizer built into the jitter cannot do its job.
Put a loop around the code to run it 10 times, it helps to get rid of overhead and measure standard deviation, always very high on very fast code like this. Go to the Release build and run it with Ctrl + F5. Now you get a real performance of this code, which should be in the south of ~ 1.5 seconds. Here's how long the loops go, none of the point code is removed by the optimizer. This can be done because the variable a not used anywhere, and the constructor has no observable side effects.
Having code that you want to completely remove is a classic threat. This can be prevented by pulling the variable a from the loop and using:
Console.WriteLine("{0}", sw.ElapsedMilliseconds, a);
Now the optimizer can no longer eliminate the point code, since the variable is used outside the loop. You will find out that you are comparing this correctly if it is still just as fast. It just doesn't matter how you initialize the structure. Learn more about what the jitter optimizer does in this post .
source share