SHARE
TWEET

Struct Performance and beforefieldinit

a guest Nov 16th, 2011 40 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.     public struct NoStaticCtor
  2.     {
  3.         private static int _myValue = 3;
  4.         public static int GetMyValue() { return _myValue; }
  5.     }
  6.  
  7.     public struct StaticCtor
  8.     {
  9.         private static int _myValue;
  10.         public static int GetMyValue() { return _myValue; }
  11.         static StaticCtor()
  12.         {
  13.             _myValue = 3;
  14.         }
  15.     }
  16.  
  17.     class Program
  18.     {
  19.         static void Main(string[] args)
  20.         {
  21.             long numTimes = 5000000000;
  22.             Stopwatch sw = new Stopwatch();
  23.             sw.Start();
  24.             for (long i = 0; i < numTimes; i++)
  25.             {
  26.                 NoStaticCtor.GetMyValue();
  27.             }
  28.             sw.Stop();
  29.             Console.WriteLine("No static ctor: {0}", sw.Elapsed);
  30.  
  31.             sw.Restart();
  32.             for (long i = 0; i < numTimes; i++)
  33.             {
  34.                 StaticCtor.GetMyValue();
  35.             }
  36.             sw.Stop();
  37.             Console.WriteLine("with static ctor: {0}", sw.Elapsed);
  38.  
  39.             sw.Restart();
  40.             for (long i = 0; i < numTimes; i++)
  41.             {
  42.                 NoStaticCtor.GetMyValue();
  43.             }
  44.             sw.Stop();
  45.             Console.WriteLine("No static ctor: {0}", sw.Elapsed);
  46.  
  47.             sw.Restart();
  48.             for (long i = 0; i < numTimes; i++)
  49.             {
  50.                 StaticCtor.GetMyValue();
  51.             }
  52.             sw.Stop();
  53.             Console.WriteLine("with static ctor: {0}", sw.Elapsed);
  54.         }
  55.     }
  56.  
  57. -----
  58. No static ctor: 00:00:03.3342359
  59. with static ctor: 00:00:14.6139917
  60. No static ctor: 00:00:03.2229995
  61. with static ctor: 00:00:12.9524860
  62. Press any key to continue . . .
  63.  
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top