Reputation: 1870
I have a custom Dictionary<T>
that has a backing collection of KeyedCollection
. While trying to optimize performance issues that I'm seeing while running in a profiler, I noticed that the IndexOf(T key)
is one of my problem areas. The code is currently implemented as the following:
public int IndexOf(TKey key)
{
if (keyedCollection.Contains(key))
{
return keyedCollection.IndexOf(keyedCollection[key]);
}
else
{
return -1;
}
}
I know that both Contains(T key)
and IndexOf(T key)
have big-O runtimes of O(n) and have confirmed this on the MSDN site. (https://msdn.microsoft.com/en-us/library/ms132438(v=vs.110).aspx)
I thought a good way to optimize this code would be to take out one of the O(n) operations, so I changed the code to this:
public int IndexOf(TKey key)
{
try
{
return keyedCollection.IndexOf(keyedCollection[key]);
}
catch (KeyNotFoundException)
{
return -1;
}
}
When I compared the runtimes between the 2 over about 500,000 operations, the code with the Contains(T key)
out performed the try-catch scenario by a factor of nearly 2.
My question is, is there a huge amount of overhead when using a try-catch block that would greatly decrease performance?
Upvotes: 0
Views: 1275
Reputation: 203842
Throwing an exception here is going to be O(1), because the cost of throwing and catching the exception is in no way dependent on the size of the collection; it's going to be a fixed cost. That fixed cost may be high, but it won't grow.
Upvotes: 3