title: Performance loss caused by Linq
body: <p>A recent update has caused significant performance loss in my code. By using a profiler I found that the loss was caused by one single line using Linq. I did some testing and found that Linq was much slower than <code>foreach</code>.</p>
  
  <pre><code>        List&lt;int&gt; numbers = new List&lt;int&gt;();
          for (int i = 0; i &lt; 1000; ++i)
              numbers.Add(i);
          var stopWatch = new Stopwatch();
  
          {
              int total = 0;
              for (int i = 0; i &lt; 1000; ++i)
                  total += i;
          }
          stopWatch.Start();
          for (int j = 0; j &lt; 1000000; ++j)
          {
              int total = 0;
              for (int i = 0; i &lt; 1000; ++i)
                  total += i;
          }
          stopWatch.Stop();
          Console.WriteLine("Benchmark run time: {0}", stopWatch.ElapsedMilliseconds);
  
          {
              int total = 0;
              foreach (int i in numbers)
                  total += i;
          }
          stopWatch.Restart();
          for (int j = 0; j &lt; 1000000; ++j)
          {
              int total = 0;
              foreach (int i in numbers)
                  total += i;
          }
          stopWatch.Stop();
          Console.WriteLine("foreach run time: {0}", stopWatch.ElapsedMilliseconds);
  
          {
              int total = 0;
              total += numbers.Sum();
          }
          stopWatch.Restart();
          for (int j = 0; j &lt; 1000000; ++j)
          {
              int total = 0;
              total += numbers.Sum();
          }
          stopWatch.Stop();
          Console.WriteLine("Sum run time: {0}", stopWatch.ElapsedMilliseconds);
  </code></pre>
  
  <p>Output:</p>
  
  <blockquote>
    <p>Benchmark run time: 653
    foreach run time: 3862
    Sum run time: 10233</p>
  </blockquote>
  
  <p>Does this mean we should always avoid using Linq in performance-critical sections?</p>
  
  <p>Update:
  Fixed the bug that stopwatch is not reset
  Do each test once before start the stopwatch for JIT
  Yes this is in release mode, and is without debugging</p>