Getting best practice vocabulary

I recently noticed a Dictionary.TryGetValue(TKey key, out TValue value) , and I was curious which one is better suited to get the value from the Dictionary.

I traditionally did:

 if (myDict.Contains(someKey)) someVal = myDict[someKey]; ... 

if I do not know that he should be there.

Better to just do:

 if (myDict.TryGetValue(somekey, out someVal) ... 

Which one is better? Faster than the other? I would suggest that the Try version will be slower than its β€œswallowing” try / catch within itself and using this as logic, no?

Thank!

+73
dictionary c #
Dec 18 '08 at 16:48
source share
3 answers

TryGetValue is a little faster because FindEntry will only be called once.

How much faster? It depends on the data set at hand. When you call Contains a method, the dictionary performs 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.

FYI: Actually, this is not a mistake.

It calls:

 public bool TryGetValue(TKey key, out TValue value) { int index = this.FindEntry(key); if (index >= 0) { value = this.entries[index].value; return true; } value = default(TValue); return false; } 

ContainsKey:

 public bool ContainsKey(TKey key) { return (this.FindEntry(key) >= 0); } 
+77
Dec 18 '08 at 16:53
source share

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.

+25
Dec 18 '08 at 17:02
source share

I assume that trygetvalue does something more:

 if(myDict.ReallyOptimisedVersionofContains(someKey)) { someVal = myDict[someKey]; return true; } return false; 

So hopefully don't try / catch anywhere.

I think this is just a convenience method. I usually use it as it saves a line of code or two.

0
Dec 18 '08 at 16:54
source share



All Articles