简体   繁体   English

大O运行时异常

[英]Big O Runtime of Exceptions

I have a custom Dictionary<T> that has a backing collection of KeyedCollection . 我有一个自定义的Dictionary<T> ,它具有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. 在尝试优化在探查器中运行时遇到的性能问题时,我注意到IndexOf(T key)是我的问题领域之一。 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. 我知道Contains(T key)IndexOf(T key)都具有O(n)的big-O运行时,并且已经在MSDN站点上确认了这一点。 ( https://msdn.microsoft.com/en-us/library/ms132438(v=vs.110).aspx ) https://msdn.microsoft.com/zh-cn/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: 我认为优化此代码的一种好方法是删除O(n)操作之一,因此我将代码更改为:

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. 当我比较这两个大约超过500,000个操作之间的运行时时,带有Contains(T key)的代码执行了try-catch场景的比例接近2。

My question is, is there a huge amount of overhead when using a try-catch block that would greatly decrease performance? 我的问题是,使用try-catch块时是否会产生大量开销,从而大大降低性能?

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; 这里抛出一个异常将是O(1),因为抛出和捕获该异常的代价绝不取决于集合的大小。 it's going to be a fixed cost. 这将是固定成本。 That fixed cost may be high, but it won't grow. 该固定成本可能很高,但不会增长。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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