更重要的是有效的:字典TryGetValue或+的containsKey项目? [英] What is more efficient: Dictionary TryGetValue or ContainsKey+Item?

查看:389
本文介绍了更重要的是有效的:字典TryGetValue或+的containsKey项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从MSDN对 Dictionary.TryGetValue方法:

这方法结合了ContainsKey方法的功能和
  Item属性。

This method combines the functionality of the ContainsKey method and the Item property.

如果没有找到键,则该值参数都可获得相应的
  对于值类型TValue默认值;例如,0(零)为
  整型,假布尔类型和空引用类型。

If the key is not found, then the value parameter gets the appropriate default value for the value type TValue; for example, 0 (zero) for integer types, false for Boolean types, and null for reference types.

使用TryGetValue方法,如果你的code频频企图访问
  密钥不在字典中。使用这种方法是更
  比捕捉由项目引发的KeyNotFoundException高效
  属性。

Use the TryGetValue method if your code frequently attempts to access keys that are not in the dictionary. Using this method is more efficient than catching the KeyNotFoundException thrown by the Item property.

这方法接近一个O(1)操作。

This method approaches an O(1) operation.

从描述,如果是更有效的,或只是不是调用的containsKey,然后做查找更方便尚不清楚。是否 TryGetValue 的实施只需要调用的containsKey然后项目或实际上比这更有效的做单查询?

From the description, it's not clear if it is more efficient or just more convenient than calling ContainsKey and then doing the lookup. Does the implementation of TryGetValue just call ContainsKey and then Item or is actually more efficient than that by doing a single lookup?

在换句话说,是更有效的(即,其中一个执行以下查找):

In other words, what is more efficient (i.e. which one performs less lookups):

Dictionary<int,int> dict;
//...//
int ival;
if(dict.ContainsKey(ikey))
{
  ival = dict[ikey];
}
else
{
  ival = default(int);
}

Dictionary<int,int> dict;
//...//
int ival;
dict.TryGetValue(ikey, out ival);

请注意:我不是在寻找一个标杆

Note: I am not looking for a benchmark!

推荐答案

TryGetValue 会更快。

的containsKey 使用相同的支票 TryGetValue ,其内部是指实际的入口位置。在项目属性实际上有几乎相同的code功能 TryGetValue ,除了它会抛出一个异常,而不是返回false。

ContainsKey uses the same check as TryGetValue, which internally refers to the actual entry location. The Item property actually has nearly identical code functionality as TryGetValue, except that it will throw an exception instead of returning false.

使用的containsKey 接着项基本上复制了查找功能,这是在此情况下,计算的体积。

Using ContainsKey followed by the item basically duplicates the lookup functionality, which is the bulk of the computation in this case.

这篇关于更重要的是有效的:字典TryGetValue或+的containsKey项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆