title: Hash table faster in C# than C++?
body: <p>Here's a curiosity I've been investigating.  The .NET Dictionary class performs ridiculously fast compared to the STL unordered_map in a test I keep running, and I can't figure out why.</p>
  
  <p>(0.5 seconds vs. 4 seconds on my machine)
  (.NET 3.5 SP1 vs. Visual Studio 2008 Express SP1's STL)</p>
  
  <p>On the other hand, if I implement my own hash table in C# and C++, the C++ version is about twice as fast as the C# one, which is fine because it reinforces my common sense that native machine code is sometimes faster.  (See.  I said "sometimes".)  Me being the same person in both languages, I wonder what tricks was the C# coder from Microsoft able to play that the C++ coder from Microsoft wasn't?  I'm having trouble imagining how a compiler could play such tricks on its own, going through the trouble of optimizing what should look to it to be arbitrary function calls.</p>
  
  <p>It's a simple test, storing and retrieving integers.</p>
  
  <p>C#:</p>
  
  <pre><code>const int total = (1 &lt;&lt; 20);
  int sum = 0;
  Dictionary&lt;int, int&gt; dict = new Dictionary&lt;int, int&gt;();
  for(int i = 0; i &lt; total; i++)
  {
      dict.Add(i, i * 7);
  }
  
  for(int j = 0; j &lt; (1 &lt;&lt; 3); j++)
  {
      int i = total;
      while(i &gt; 0)
      {
          i--;
          sum += dict[i];
      }
  }
  Console.WriteLine(sum);
  </code></pre>
  
  <p>C++:</p>
  
  <pre><code>const int total = (1 &lt;&lt; 20);
  int sum = 0;
  std::tr1::unordered_map&lt;int, int&gt; dict;
  for(int i = 0; i &lt; total; i++)
  {
      dict.insert(pair&lt;int, int&gt;(i, i * 7));
  }
  
  for(int j = 0; j &lt; (1 &lt;&lt; 3); j++)
  {
      int i = total;
      while(i &gt; 0)
      {
          i--;
          std::tr1::unordered_map&lt;int, int&gt;::const_iterator found =
              dict.find(i);
          sum += found-&gt;second;
      }
  }
  cout &lt;&lt; sum &lt;&lt; endl;
  </code></pre>