Comparison between Frozen, Immutable and Dictionary
Microsoft’s upcoming release of .NET 8 will introduce a lot of new features that will certainly be welcomed by the developer community, making it an even stronger framework for application development.
One of those features is the namespace System.Collections.Frozen that introduces two new collections: FrozenDictionary and FrozenSet. These new types, as stated by Microsoft, are focused in reducing the time of read operations at the expense of increasing initialization time of immutable collections. This makes them perfect for shared data that only needs to be populated a single time, like application configurations or cached data in-memory.
In this article I’m going to benchmark the performance gains that can be achieved by using a FrozenDictionary instead of a Dictionary or an ImmutableDictionary to store shared data.
I’m going to use the well known C# library BenchmarkDotNet to run the tests and the environment will be the following:
For the tests, I’m going to benchmark the method TryGetValue, with one for 100% key hits and another for 100% key misses, which should give the performance for both perfect and worse scenarios. The collections FrozenDictionary, ImmutableDictionary and Dictionary will be used with a parameter setting the size.
Scenario 1 — all keys are found
For this scenario I’m going to initialize a collection of unique keys, populate all three dictionaries accordingly and then run the TryGetValue for all keys returning the latest found using the Dictionary test as the baseline.
As you can see, except for very small collections, the FrozenDictionary is about 43% faster than using a Dictionary, much faster than an ImmutableDictionary, without allocating more memory.
Scenario 2 — no keys are found
For this scenario I’m going to initialize a collection of unique keys, populate all three dictionaries accordingly, convert all keys to negative numbers to ensure the lookups are all different but will never match, and then run the TryGetValue for all returning the latest found using the Dictionary test as the baseline.
As you can see, the FrozenDictionary is on average 47% faster than a Dictionary for all sizes and even uses less memory for bigger collections. The ImmutableDictionary, once again, is the worse performer.
Conclusion
Microsoft with the release of .NET 8 is, once again, providing a lot of performance improvements that developers can use in their applications.
For this article in particular, if you are storing key-value reference data that is immutable, populated a single time and can be shared across your application, the FrozenDictionary may be a good option if performance is of concern.
Soon I’ll also do a benchmark for FrozenSet which I expect should demonstrate similar results.