title: Optimizing Aggregate for String Concatenation
body: <p><strong>Update</strong> - for those of a facetious frame of mind, you can assume that Aggregate still produces the normal result whatever function is passed to it, including in the case being optimized.</p>
  <p>I wrote this program to build a long string of integers from 0 to 19999 separate by commas.</p>
  <pre><code>using System;
  using System.Linq;
  using System.Diagnostics;
  
  namespace ConsoleApplication5
  {
      class Program
      {
          static void Main(string[] args)
          {
              const int size = 20000;
  
              Stopwatch stopwatch = new Stopwatch();
  
              stopwatch.Start();
              Enumerable.Range(0, size).Select(n =&gt; n.ToString()).Aggregate((a, b) =&gt; a + &quot;, &quot; + b);
              stopwatch.Stop();
  
              Console.WriteLine(stopwatch.ElapsedMilliseconds + &quot;ms&quot;);
          }
      }
  }
  </code></pre>
  <p>When I run it, it says:</p>
  <pre><code>5116ms
  </code></pre>
  <p>Over five seconds, terrible. Of course it's because the whole string is being copied each time around the loop.</p>
  <p>But what if make one very small change indicated by the comment?</p>
  <pre><code>using System;
  using System.Linq;
  using System.Diagnostics;
  
  namespace ConsoleApplication5
  {
      using MakeAggregateGoFaster;  // &lt;---- inserted this
  
      class Program
      {
          static void Main(string[] args)
          {
              const int size = 20000;
  
              Stopwatch stopwatch = new Stopwatch();
  
              stopwatch.Start();
              Enumerable.Range(0, size).Select(n =&gt; n.ToString()).Aggregate((a, b) =&gt; a + &quot;, &quot; + b);
              stopwatch.Stop();
  
              Console.WriteLine(stopwatch.ElapsedMilliseconds + &quot;ms&quot;);
          }
      }
  }
  </code></pre>
  <p>Now when I run it, it says:</p>
  <pre><code>42ms
  </code></pre>
  <p>Over 100x faster.</p>
  <h3>Question</h3>
  <p>What's in the MakeAggregateGoFaster namespace?</p>
  <p><strong>Update 2:</strong> <a href="http://incrediblejourneysintotheknown.blogspot.com/2008/12/optimizing-aggregate-for-string.html" rel="noreferrer">Wrote up my answer here</a>.</p>