title: Optimize Dictionary Add on ExpandoObjects in C#
body: <p>I have an advanced program that retrieves data from a database and creates objects from the data via ExpandoObjects in C#. </p>
  
  <p>I'm now in the process of optimizing my entire process but came upon a piece of code that was the bottleneck performance-wise. I am quite curious how far I can furhter optimize this piece of code and already managed to run it 3 times as fast by doing the following:</p>
  
  <ul>
  <li>Seperated <em>'the finding 'types' section'</em> in a seperate for loop and only iterate over it when it hasn't been initialized yet.</li>
  <li><p>Added a case for when the value is null and create an empty string instead, since for some reason Dictionary.Add slows down quite a lot when adding Null values. </p>
  
  <pre><code>    // Holds all objects that are created inside the object.
      Dictionary&lt;string, IDictionary&lt;string, dynamic&gt;&gt; objects = new Dictionary&lt;string, IDictionary&lt;string, dynamic&gt;&gt;();
  
      // This foreach loop is the slowest part!
      foreach (KeyValuePair&lt;string, dynamic&gt; pair in fields)
      {
          string type = pair.Key.Split('_')[0];
  
          IDictionary&lt;string, dynamic&gt; obj;
          if (!objects.TryGetValue(type, out obj))
          {
              obj = new ExpandoObject();
              objects.Add(type, obj);
          }
          int location = pair.Key.IndexOf(type + "_");
          string key = pair.Key.Remove(location, type.Length + 1);
          if (pair.Value == null)         // If Value is null, replace it with an empty string (dictionary slows quite alot when passing it null values)
              obj.Add(key, "");
          else
              obj.Add(key, pair.Value);         
      }
  
      if (types == null)
          types = objects.Select(x =&gt; x.Key).ToList();
  </code></pre></li>
  </ul>
  
  <p>I am wondering, how is it that dictionary slows down that much when adding Null values, is it that in the underlying structure it does special operations when encountering null values? And is there something I'm missing to further optimize the code?.</p>
  
  <p>Any help is again greatly appreciated.</p>
  
  <p><hr/>
  <strong>UPDATE</strong></p>
  
  <ul>
  <li>Edited the code with the most recent changes I've gathered from SO.</li>
  </ul>