Today I saw some code where the developer accessed a dictionary like this:
As you can see he catches the exception to handle the fact that the given key was not found in the dictionary.
I told him that there was a better way, i.e. Dictionary<TKey, TValue>.TryGetValue.
And then the curious part of me started thinking, how much better is it? Is it faster? Slower?
So I wrote the following small piece of code to test my statement that TryGetValue is better than catching the KeyNotFoundException.
As you can see we add 10,000 items to the dictionary, skipping the 5000th item, and then we do a lookup in the dictionary, 10,000 times, on the key that doesn’t exist, to measure the performance difference between the 2 previously discussed methods.
To run this test I did a Release Build in Visual Studio 2010, .NET 4.0, Any CPU, and this is the result:
Dictionary lookup with try/catch took: 1069625
Dictionary lookup with TryGetValue took: 864
Done, press enter to exit
As you can see there is a HUGE difference. The TryGetValue-way was about 1237 faster!
Exception throwing is very heavy! Don’t forget that. It doesn’t mean that you need to program without exceptions, but when you EXPECT that a Key is not present in a given dictionary, don’t use the exception. Use the TryGetValue. If you always expect it to be there then it’s normal to catch the exception, because it’s exceptional that the key was not found.
PS: I tried the code again by skipping the 9999th item, and the results were about the same, take or leave a few milliseconds. So searching in the dictionary is very performant (close to O(1), as written in the Remarks section on this page.)