title: What does a hashset do with memory when initializing a collection?
body: <p>I stumbled upon the following problem.<br>
  I want a hashset with all numbers from 1 to 100.000.000.
  I tried the following code:</p>
  
  <pre><code>var mySet = new HashSet&lt;int&gt;();
  for (var k = 1; k &lt;= 100000000; k++)
       mySet.Add(k);
  </code></pre>
  
  <p>That code didn't make it since I got memory overflow somewhere around the 49mil. This was also pretty slow and memory grew excessively.</p>
  
  <p>Then I tried this.</p>
  
  <pre><code>var mySet = Enumerable.Range(1, 100000000).ToHashSet();
  </code></pre>
  
  <p>where ToHashSet() is the following code:</p>
  
  <pre><code>public static HashSet&lt;T&gt; ToHashSet&lt;T&gt;(this IEnumerable&lt;T&gt; source)
  {
      return new HashSet&lt;T&gt;(source);
  }
  </code></pre>
  
  <p>I got a memory overflow again but I was able to put in more numbers then with the previous code.</p>
  
  <p>The thing that does work is the following:</p>
  
  <pre><code>var tempList = new List&lt;int&gt;();
  for (var k = 1; k &lt;= 100000000; k++)
       tempList.Add(k);
  
  var numbers = tempList.ToHashSet();
  </code></pre>
  
  <p>It takes about 800ms on my system to just fill the tempList where the Enumerable.Range() only takes 4 ticks!</p>
  
  <p>I do need that HashSet or else it would take to much time to lookup values (I need it to be O(1)) and it would be great if I could do that the fastest way.</p>
  
  <p>Now my question is:<br>
   <strong>Why do the first two methods cause a memory overflow where the third doesn't?</strong></p>
  
  <p>Is there something special HashSet does with the memory on initializing?</p>
  
  <p>My system has 16GB memory so i was quite surprised when I got the overflow exceptions.</p>