title: Fast parallel adding to dictionary when keys never collide
body: <p>I have a situation, where dictionary is created, key-value pairs are added, and after that point dictionary is used only for reading values.</p>
  
  <p>I'm trying to implement quickest way of adding to dictionary in the initialization phase.</p>
  
  <p>ConcurrentDictionary has very slow TryAdd method (and also GetOrAdd) - on my 6 core CPU (12 threads), CPU usage usually stays at 25%, indicating that only 3 threads are used.</p>
  
  <p>It is actually faster to add all keys (around 25 million) to Dictionary sequentially, than using ConcurrentDictionary and Parallel.For.</p>
  
  <p>How can I improve speed here?
  It is easy to separate key-value pairs, so that keys never collide when added to dictionary, but just using code below creates some problems:</p>
  
  <pre><code>Dictionary&lt;long,string&gt; d = new Dictionary&lt;long,string&gt;();
  d[key] = value;
  </code></pre>
  
  <p>It seems that this, when used in multi-threaded environment, fails because Dictionary does some internal changes sometimes (resizing?).</p>
  
  <p>Would this work instead?</p>
  
  <pre><code>capacity = 250000000 //basically big enough to store all data
  Dictionary&lt;long,string&gt; d = new Dictionary&lt;long,string&gt;(capacity);
  d[key] = value;
  </code></pre>
  
  <p>I much prefer using Dictionary over ConcurrentDictionary, because reads are much faster too (and speed is crucial for my application).</p>