.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.