comment 0

Professional Development – 2025 – Week 4

Image Credit: https://www.flickr.com/photos/54585499@N04/

.NET

Fixing Your Dictionary Problem in .NET

A common scenario is checking if a key exists before inserting it. This causes two passes through the hashing algorithm — lookup, insertion. Note that ConcurrentDictionary<T> has a GetOrAdd() method. You can make your own extension method that does this via CollectionsMarshal.GetValueRefOrAddDefault(). You can also use .GetValueRefOrNullRef() to implement a “try update” method. This will have small performance benefits (i.e., nanoseconds) but can be significant if many operations involve adding/updating dictionaries.

Leave a Reply

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


This site uses Akismet to reduce spam. Learn how your comment data is processed.