Wednesday, June 1, 2011

(.NET 2.) Dictionary(Of Key, Value) performance trick

What's often overlooked is a performance penalty with this pattern shift. Because of the exception, people will do something like this:
MyClass toReturn;
if(!_myDictionary.ContainsKey(key))
{
toReturn = _myDictionary[key];
}
else
{
toReturn = new MyClass();
}

Pretty obvious code, right? Well, ok, but it has a performance penalty which isn't that obvious: you'll query the key index twice: once in the ContainsKey call and once in the _myDictionary[key] call. If you query your dictionary a lot of times, even if the dictionary is fairly small, it will hurt performance. Better do:

MyClass toReturn = null;
if(!_myDictionary.TryGetValue(key, out toReturn))
{
 toReturn = new MyClass();
}
During profile sessions of my code I found a lot of these misusages in my .NET 2.0

 if (dict.ContainsKey("Key1"))
            dict
["Key1"] = "Value1";
       
else
            dict
.Add("Key1", "Value1");
You can simplify your 4 lines of code to this:

dict["Key1"] = "Value1"; 

No comments:

Post a Comment