title: Why is it faster to check if dictionary contains the key, rather than catch the exception in case it doesn't?
body: <p>Imagine the code:</p>
  
  <pre><code>public class obj
  {
      // elided
  }
  
  public static Dictionary&lt;string, obj&gt; dict = new Dictionary&lt;string, obj&gt;();
  </code></pre>
  
  <p><strong>Method 1</strong></p>
  
  <pre><code>public static obj FromDict1(string name)
  {
      if (dict.ContainsKey(name))
      {
          return dict[name];
      }
      return null;
  }
  </code></pre>
  
  <p><strong>Method 2</strong></p>
  
  <pre><code>public static obj FromDict2(string name)
  {
      try
      {
          return dict[name];
      }
      catch (KeyNotFoundException)
      {
          return null;
      }
  }
  </code></pre>
  
  <p>I was curious if there is a difference in performance of these 2 functions, because the first one SHOULD be SLOWER than second one - given that it needs to check twice if the dictionary contains a value, while second function does need to access the dictionary only once but WOW, it's actually opposite:</p>
  
  <p>Loop for 1 000 000 values (with 100 000 existing and 900 000 non existing):</p>
  
  <blockquote>
    <p>first function: 306 milliseconds</p>
    
    <p>second function: 20483 milliseconds</p>
  </blockquote>
  
  <p>Why is that?</p>
  
  <p>EDIT: As you can notice in comments below this question, the performance of second function is actually slightly better than first one in case there are 0 non existing keys. But once there is at least 1 or more non existing keys, the performance of second one decrease rapidly.</p>