Retrieving Dictionary Value Best Practices

C#.NetDictionary

C# Problem Overview


I just recently noticed Dictionary.TryGetValue(TKey key, out TValue value) and was curious as to which is the better approach to retrieving a value from the Dictionary.

I've traditionally done:

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

unless I know it has to be in there.

Is it better to just do:

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

Which is the better practice? Is one faster than the other? I would imagine that the Try version would be slower as its 'swallowing' a try/catch inside itself and using that as logic, no?

C# Solutions


Solution 1 - C#

TryGetValue is slightly faster, because FindEntry will only be called once.

> How much faster? It depends on the > dataset at hand. When you call the > Contains method, 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 found, > it assigns the value to your variable.

FYI: It's not actually catching an error.

It's calling:

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 is this:

public bool ContainsKey(TKey key)
{
    return (this.FindEntry(key) >= 0);
}

Solution 2 - C#

Well in fact TryGetValue is faster. How much faster? It depends on the dataset at hand. When you call the Contains method, 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 found, it assigns the value to your variable.

Edit:

Ok, I understand your confusion so let me elaborate:

Case 1:

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

In this case there are 2 calls to FindEntry, one to check if the key exists and one to retrieve it

Case 2:

myDict.TryGetValue(somekey, out someVal)

In this case there is only one call to FindKey because the resulting index is kept for the actual retrieval in the same method.

Solution 3 - C#

I imagine that trygetvalue is doing something more like:

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

So hopefully no try/catch anywhere.

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

Solution 4 - C#

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

public bool ContainsKey(TKey key)
{
  return (this.FindEntry(key) >= 0);
}

Like you can see TryGetValue is same as ContainsKey + one array lookup.

If your logic is only to check if the key is existing in the Dictionary and nothing else related to this key (taking the value for the key) you should use ContainsKey.

Try also checking this similar question: is-there-a-reason-why-one-should-use-containskey-over-trygetvalue

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNicholas MancusoView Question on Stackoverflow
Solution 1 - C#MicahView Answer on Stackoverflow
Solution 2 - C#DiadistisView Answer on Stackoverflow
Solution 3 - C#JenniferView Answer on Stackoverflow
Solution 4 - C#dubiView Answer on Stackoverflow