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!
This question is related to
c#
performance
dictionary
Source: Stackoverflow.com