Case for TryGetValue

When I am reviewing code, I always check how program retrieved items from dictionary. Most often I find following pattern:

if (dict.ContainsKey(key)) {
object obj = dict[key];
//do something with obj
}

Whenever I see it, I wonder why somebody would use it over TryGetValue:

object obj;
if (dict.TryGetValue(i, out obj)) {
//do something with obj
}

If you deal with dictionary of objects, later code is something around 25% (depends on size of dictionary and bunch of other stuff) faster. If you deal with dictionary of structures, difference is much smaller (7-8%) since in later case you need to deal with memory allocations (remember that there is no null for structures).

Most of the time, dictionaries are used in time critical code so changing code to later is almost a no-brainer.

I only ever came to see one single scenario where key check separated from retrieval is desired. On case your dictionary has structures in it and you expect lot of look-up failures you will be better off using first example. Second code will use much more memory and need to create structure before each key check will offset any time savings you might get when item is found.

One thought to “Case for TryGetValue”

  1. I love Objective-C’s default way of handling this, and I can’t think of a downside. I presume that’s the same thing as what TryGetValue() does in C#: key is looked up only once, and if the value is not found, nil is returned.

    NSString * theValue = [theDictionary objectForKey:@”someKey”];
    if(theValue)
    {
    // do something with the value
    }

Leave a Reply

Your email address will not be published. Required fields are marked *