title: .NET: ThreadStatic vs lock { }. Why ThreadStaticAttribute degrades performance?
body: <p>I've written small test program and was surprised why <code>lock {}</code> solution performs faster than lock-free but with <code>[ThreadStatic]</code> attribute over static variable.</p>
  
  <p>[ThreadStatic] snippet:</p>
  
  <pre><code>[ThreadStatic]
  private static long ms_Acc;
  public static void RunTest()
  {
      Stopwatch stopwatch = new Stopwatch();
      stopwatch.Start();
      int one = 1;
      for (int i = 0; i &lt; 100 * 1000 * 1000; ++i) {
          ms_Acc += one;
          ms_Acc /= one;
      }
      stopwatch.Stop();
      Console.WriteLine("Time taken: {0}", stopwatch.Elapsed.TotalSeconds);
  }
  </code></pre>
  
  <p>lock {} snippet:</p>
  
  <pre><code>private static long ms_Acc;
  private static object ms_Lock = new object();
  public static void RunTest()
  {
      Stopwatch stopwatch = new Stopwatch();
      stopwatch.Start();
      int one = 1;
      for (int i = 0; i &lt; 100 * 1000 * 1000; ++i) {
          lock (ms_Lock) {
              ms_Acc += one;
              ms_Acc /= one;
          }
      }
      stopwatch.Stop();
      Console.WriteLine("Time taken: {0}", stopwatch.Elapsed.TotalSeconds);
  }
  </code></pre>
  
  <p>On my machine first snippet takes 4.2 seconds; second - 3.2 seconds, which is 1 second faster. Without ThreadStatic and lock - 1.2 seconds.</p>
  
  <p>I'm curious why <code>[ThreadStatic]</code> attribute in this simple example adds so many to program execution time?</p>
  
  <p><strong>UPDATE</strong>: I feel very sorry, but these results are for <code>DEBUG</code> build. For <code>RELEASE</code> one I got completely different numbers: (1.2; 2.4; 1.2). For <code>DEBUG</code> numbers were (4.2; 3.2; 1.2).</p>
  
  <p><strong>So, for <code>RELEASE</code> build there seems to be no <code>[ThreadStatic]</code> performance penalty.</strong></p>