mottishaked

See: http://bit.ly/tZfVs9

Nov 16th, 2011
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.70 KB | None | 0 0
  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.     const long numTimes = 5000000000;
  20.        
  21.     static void Main(string[] args)
  22.     {
  23.         NoCtor1();
  24.         WithCtor1();
  25.  
  26.         NoCtor2();
  27.         WithCtor2();
  28.     }
  29.  
  30.     private static void NoCtor1()
  31.     {
  32.         Stopwatch sw = new Stopwatch();
  33.         sw.Start();
  34.         for (long i = 0; i < numTimes; i++)
  35.         {
  36.             NoStaticCtor.GetMyValue();
  37.         }
  38.         sw.Stop();
  39.         Console.WriteLine("No static ctor: {0}", sw.Elapsed);
  40.     }
  41.  
  42.     private static void NoCtor2()
  43.     {
  44.         Stopwatch sw = new Stopwatch();
  45.         sw.Start();
  46.         for (long i = 0; i < numTimes; i++)
  47.         {
  48.             NoStaticCtor.GetMyValue();
  49.         }
  50.         sw.Stop();
  51.         Console.WriteLine("No static ctor: {0}", sw.Elapsed);
  52.     }
  53.  
  54.     private static void WithCtor1()
  55.     {
  56.         Stopwatch sw = new Stopwatch();
  57.         sw.Start();
  58.         for (long i = 0; i < numTimes; i++)
  59.         {
  60.             StaticCtor.GetMyValue();
  61.         }
  62.         sw.Stop();
  63.         Console.WriteLine("with static ctor: {0}", sw.Elapsed);
  64.     }
  65.  
  66.     private static void WithCtor2()
  67.     {
  68.         Stopwatch sw = new Stopwatch();
  69.         sw.Start();
  70.         for (long i = 0; i < numTimes; i++)
  71.         {
  72.             StaticCtor.GetMyValue();
  73.         }
  74.         sw.Stop();
  75.         Console.WriteLine("with static ctor: {0}", sw.Elapsed);
  76.     }
  77. }
  78.  
  79.  
Add Comment
Please, Sign In to add comment