c# - 什么更有效率 : Dictionary TryGetValue or ContainsKey+Item?

标签 c# performance dictionary

来自 MSDN 关于 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.

从描述来看,不清楚它是否比调用 ContainsKey 然后进行查找更有效或更方便。 TryGetValue 的实现是仅调用 ContainsKey 然后调用 Item 还是实际上比通过执行单个查找更有效?

换句话说,哪个更有效(即哪个执行的查找次数更少):

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

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

最佳答案

TryGetValue 会更快。

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

使用 ContainsKey 后接 Item 基本上复制了查找功能,这是本例中的大部分计算。

关于c# - 什么更有效率 : Dictionary TryGetValue or ContainsKey+Item?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9382681/

相关文章:

performance - 检查 14 位数字是否为质数的最快算法是什么?

c# - 为什么我的应用程序调用这么慢?

dictionary - 为什么 map 中没有键

python - 根据 .CSV 文件中字典键的出现次数进行计数

c# - 我应该为枚举成员使用什么 AttributeTarget?

C++ 多次写入文件的有效方法

c# - 当参数之一是动态时,如何获取类型的构造函数?

python - 在数据库中存储 700 万个键的 python 字典

c# - 从 C++ 到 C# .Net Compact Framework 的结构转换问题

c# - 通过插件在 Unity 中使用 Apple idfa