来自 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/