哪个更有效:Dictionary TryGetValue 或 ContainsKey+Item? [英] What is more efficient: Dictionary TryGetValue or ContainsKey+Item?

查看:27
本文介绍了哪个更有效:Dictionary TryGetValue 或 ContainsKey+Item?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 MSDN 关于 Dictionary.TryGetValue Method 的条目:

From MSDN's entry on Dictionary.TryGetValue Method:

该方法结合了 ContainsKey 方法的功能和Item 属性.

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

如果没有找到key,则value参数获取相应的值类型 TValue 的默认值;例如,0(零)表示整数类型,布尔类型为 false,引用类型为 null.

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 方法字典中没有的键.用这个方法比较比捕获 Item 抛出的 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 然后调用 Item 还是实际上比通过单次查找更有效?

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 相同的检查,它在内部引用实际的入口位置.Item 属性实际上具有与 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 后跟 Item 基本上复制了查找功能,这是本例中的大部分计算.

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

这篇关于哪个更有效:Dictionary TryGetValue 或 ContainsKey+Item?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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