Actually TryGetValue is faster. How much faster? It depends on the data set. When you call the Contains method, the dictionary does an internal search to find its index. If it returns true, you need another index search to get the actual value. When you use TryGetValue, it searches only once for the index, and if it is found, it assigns the value to your variable.
Edit:
Ok, I understand your confusion, so let me clarify:
Case 1:
if (myDict.Contains(someKey)) someVal = myDict[someKey];
In this case, there are two FindEntry calls, one of which checks if the key exists, and one to get it.
Case 2:
myDict.TryGetValue(somekey, out someVal)
In this case, there is only one FindKey call, because the resulting index is stored for the actual search in the same method.
Diadistis Dec 18 '08 at 17:02 2008-12-18 17:02
source share