I wrote the following extension method to get an element from a dictionary, or null if the key isn't present:
public static TValue ItemOrNull<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key)
{
try
{
return dict[key];
}
catch (KeyNotFoundException ex)
{
return default(TValue);
}
}
I noticed that my program was running very slowly so I tracked down the problem to this extension method using a high precision timer class. I get similar results ~100 times in a row:
DebugTimer.ResetTimer();
dict1.ItemOrNull(key);
dict2.ItemOrNull(key);
DebugTimer.StopTimer();
takes about 110,000,000 ticks (more than 0.03 seconds on my processor). While the more verbose version:
DebugTimer.ResetTimer();
if (dict1.ContainsKey(key))
y = dict1[key];
if (dict2.ContainsKey(key))
z = dict2[key];
DebugTimer.StopTimer();
MessageBox.Show(y.ToString(), z.ToString()) // so the compiler doesn't optimize away y and z
takes about 6,000 ticks (less than 0.000002 seconds).
Is it clear to anyone why my extension method version is taking more than 4 orders of magnitude longer than the verbose version?