256 Seconds with dotNetDave: Be careful using ContainsKey() with Dictionary Types

In this episode of “256 Seconds with dotNetDave,” I will demonstrate the performance issues associated with using ContainsKey() with Dictionary<,> types in Microsoft .NET when searching for an item within the collection.

The Code

This serves as an illustration of the problem that arises when employing ContainsKey() with Dictionary<,> types.

The issue with this code lies in the double lookup process – first when ContainsKey() is called and then again during the Update() line. This double lookup results in a performance bottleneck. To resolve this, it is recommended to use TryGetValue() instead, as demonstrated below.

TryGetValue() attempts to locate the value associated with a given key and provides that instance in the out parameter. This eliminates the need for a second lookup when passing the value to the Update() method.

Benchmark Results

These results clearly demonstrate that utilizing TryGetValue() is twice as efficient as using ContainsKey()!

Add TryGetValue for Custom Dictionary Types

Be cautious when implementing ContainsKey() in a custom type that internally uses Dictionary<,>, as exemplified in this case.

It is also advisable to implement TryGetValue() as illustrated below.

EditorConfig

To ensure that ContainsKey() issues are identified by the Visual Studio Analyzer, add the following configuration to your EditorConfig file.

# Prefer the IDictionary.TryGetValue(TKey, out TValue) method
dotnet_diagnostic.CA1854.severity = error

Other Collection Types?

I conducted tests to determine whether using FirstOrDefault() with various collection types, such as List<>, arrays, and ImmutableArray<>, might offer better performance compared to Dictionary<,>. However, the results showed that all of these alternatives were slower than using TryGetValue().

If you have any questions or comments, please don’t hesitate to share them below.

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave

© The information in this article is copywritten and cannot be reproduced in any way without express permission from David McCarter.


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

One thought on “256 Seconds with dotNetDave: Be careful using ContainsKey() with Dictionary Types

Leave a Reply