Sitemap

.NET 8 — Frozen Collections

2 min readJan 15, 2024
Press enter or click to view image in full size

⚠️ This article has moved to my website.

You can read the latest version here:
👉 https://henriquesd.com/articles/net-8-frozen-collections

Below is a short preview of the article.

Frozen Collections is a new .NET 8 feature that can be used to create Dictionaries and Sets for faster read operations when you don’t need to make changes after the creation. In this article, I present how to work with these collections and demonstrate the performance difference when compared with other collections.

The new System.Collections.Frozen namespace includes the collection types FrozenDictionary<TKey,TValue> and FrozenSet<T>, these types are optimized for fast lookup operations. They take a bit more time during the creation, but the read operations are faster when compared with a Dictionary or a Set.

FrozenDictionary and FrozenSet

A FrozenDictionary and FrozenSet provides an immutable, read-only dictionaryand set, optimized for fast lookup and enumeration. It is optimized for cases when you only need to create a dictionary/set once, and will not need to change keys or values, and it is frequently used at the run time.

They are ideal for cases when the dictionary/set is created once (potentially at the startup of the application) and used throughout the remainder of the life of the app.

To create a FrozenDictionary you can use the ToFrozenDictionary method:

FrozenDictionary<int, int> frozenDictionary = 
Enumerable.Range(0, 10).ToFrozenDictionary(key => key);

To create a FrozenSet you can use the ToFrozenSet method:

FrozenSet<int> frozenSet = Enumerable.Range(0, 10).ToFrozenSet();

Benchmark

For demonstration purposes, I create a series of methods that do three different operations for different collection types: Create the collection, execute the TryGetValue method, and execute a Lookup operation, and to run the benchmark, I used the BenchmarkDotNet package.

👉 Continue reading the full article here: https://henriquesd.com/articles/net-8-frozen-collections