什么是更有效率:Dictionary TryGetValue或ContainsKey + Item? [英] What is more efficient: Dictionary TryGetValue or ContainsKey+Item?

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

问题描述

从MSDN的 Dictionary.TryGetValue方法中的条目:


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



如果找不到键,则value参数为值类型TValue获取相应的
默认值;例如,对于
整数类型,0(零),布尔类型为false,引用类型为null。



如果您的代码经常尝试,请使用TryGetValue方法访问不在字典中的
键。使用此方法比捕获Item
属性抛出的KeyNotFoundException更有效。$ /

此方法接近O(1)操作。 / p>

从描述中,不清楚它是否比调用ContainsKey更有效或更方便,然后进行查找。执行 TryGetValue 只需调用ContainsKey,然后单击Item即可实现更高效?



<换句话说,更有效率(即哪一个执行较少的查找):

 字典< int,int>快译通; 
// ... //
intival;
if(dict.ContainsKey(ikey))
{
ival = dict [ikey];
}
else
{
ival = default(int);
}

 词典< INT,INT>快译通; 
// ... //
intival;
dict.TryGetValue(ikey,out ival);

注意:我不是在寻找基准!

解决方案

TryGetValue 将更快。



ContainsKey 使用与 TryGetValue 相同的检查,内部引用实际的入口位置。 项目属性实际上具有与 TryGetValue 几乎相同的代码功能,除了它会抛出异常而不是返回false。



使用 ContainsKey 后面的项目基本上复制了查找功能,这是这种情况下的大部分计算。


From MSDN's entry on Dictionary.TryGetValue Method:

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

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.

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.

This method approaches an O(1) operation.

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);
}

or

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

Note: I am not looking for a benchmark!

解决方案

TryGetValue will be faster.

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.

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天全站免登陆