Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public struct NoStaticCtor
- {
- private static int _myValue = 3;
- public static int GetMyValue() { return _myValue; }
- }
- public struct StaticCtor
- {
- private static int _myValue;
- public static int GetMyValue() { return _myValue; }
- static StaticCtor()
- {
- _myValue = 3;
- }
- }
- class Program
- {
- private static readonly long numTimes = 5000000000;
- static void DoFirstLoop()
- {
- Stopwatch sw = new Stopwatch();
- sw.Start();
- for (long i = 0; i < numTimes; i++)
- {
- NoStaticCtor.GetMyValue();
- }
- sw.Stop();
- Console.WriteLine("First Loop: No static ctor: {0}", sw.Elapsed);
- sw.Restart();
- for (long i = 0; i < numTimes; i++)
- {
- StaticCtor.GetMyValue();
- }
- sw.Stop();
- Console.WriteLine("First Loop: with static ctor: {0}", sw.Elapsed);
- }
- static void DoSecondLoop()
- {
- Stopwatch sw = new Stopwatch();
- sw.Start();
- for (long i = 0; i < numTimes; i++)
- {
- NoStaticCtor.GetMyValue();
- }
- sw.Stop();
- Console.WriteLine("Second Loop: No static ctor: {0}", sw.Elapsed);
- sw.Restart();
- for (long i = 0; i < numTimes; i++)
- {
- StaticCtor.GetMyValue();
- }
- sw.Stop();
- Console.WriteLine("Second Loop: with static ctor: {0}", sw.Elapsed);
- }
- static void Main(string[] args)
- {
- DoFirstLoop(); // Slow, because JITer adds the check to the loop
- DoFirstLoop(); // Still slow, because the JIT uses the cached method
- DoSecondLoop(); // Fast, because the static constructor was called in the first function, no checks added when JITed
- }
- }
- --------------
- First Loop: No static ctor: 00:00:03.5460631
- First Loop: with static ctor: 00:00:14.6650061
- First Loop: No static ctor: 00:00:03.2156631
- First Loop: with static ctor: 00:00:14.5452244
- Second Loop: No static ctor: 00:00:03.2322878
- Second Loop: with static ctor: 00:00:03.2336642
- Press any key to continue . . .
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement