简体   繁体   中英

Big O Runtime of Exceptions

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM