How to Use FrozenDictionary and FrozenSet in C# and .NET for Fast Read-Only Lookups
Many .NET applications build a lookup table once at startup—MIME type mappings, feature-flag allowlists, country codes, or route metadata—and then query it millions of times across incoming HTTP requests without ever modifying it again. Standard Dictionary<TKey, TValue> and HashSet<T> are optimized for general-purpose mutation (Add, Remove, resizing), leaving read-only lookup speed on the table. Starting in .NET 8, FrozenDictionary<TKey, TValue> and FrozenSet<T> trade extra upfront construction time for faster runtime reads.
Editorial illustration: FrozenDictionary pays a one-time creation cost at startup to optimize frequent read-only lookups.
Summary
FrozenDictionary<TKey, TValue>andFrozenSet<T>(inSystem.Collections.Frozen, introduced in .NET 8) are immutable collections optimized for read-heavy workloads where data is created infrequently and queried often.- Convert an existing
IEnumerable<KeyValuePair<K, V>>orDictionary<K, V>usingToFrozenDictionary()orToFrozenSet(). - Trade-off: Creation is noticeably slower and allocates more work upfront than
new Dictionary<K, V>(), so never build aFrozenDictionaryinside a per-request loop. - Per Microsoft Learn’s remarks, initialize
FrozenDictionaryonly with trusted keys, because key characteristics influence construction time and internal strategy selection.
Prerequisites: .NET BCL API vs. C# Language
- .NET Runtime / BCL (
System.Collections.Frozen): Available in .NET 8 and newer (including.NET 9,.NET 10, and.NET 11) without external NuGet packages. - C# Language & IDE: Works with any modern C# version targeting
net8.0+in Visual Studio 2022/2026 or VS Code with the .NET SDK.
How FrozenDictionary differs from Dictionary and ImmutableDictionary
It is easy to confuse the three read-only/immutable options in .NET:
IReadOnlyDictionary<TKey, TValue>/ReadOnlyDictionary: Just a read-only wrapper around a mutableDictionary. If someone still holds a reference to the backingDictionary, it can still mutate, and lookup speed is identical toDictionary.ImmutableDictionary<TKey, TValue>: Built around persistent balanced trees so creating a modified copy (SetItem) shares nodes efficiently. Great when you need frequent structural mutations with immutability, slower for pureTryGetValuelookups.FrozenDictionary<TKey, TValue>: True immutability with noAdd/SetItemmutation API at all. At creation time, .NET analyzes the actual keys (for example, string lengths or integer ranges) and picks an optimized internal lookup strategy—giving you the fastest runtime reads of the three.
Practical example: Static startup lookup table
Here is a clean .NET 8+ example using FrozenDictionary for case-insensitive MIME type lookups and FrozenSet for an allowed-extensions check:
using System.Collections.Frozen;
public static class MediaCatalog
{
private static readonly FrozenDictionary<string, string> MimeTypes =
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
[".png"] = "image/png",
[".jpg"] = "image/jpeg",
[".webp"] = "image/webp",
[".svg"] = "image/svg+xml",
[".pdf"] = "application/pdf",
}.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);
private static readonly FrozenSet<string> ImageExtensions =
new[] { ".png", ".jpg", ".webp", ".svg" }
.ToFrozenSet(StringComparer.OrdinalIgnoreCase);
public static bool TryGetMimeType(string extension, out string? mimeType)
=> MimeTypes.TryGetValue(extension, out mimeType);
public static bool IsSupportedImage(string extension)
=> ImageExtensions.Contains(extension);
}
Notice two practical details:
- Pass your
StringComparertoToFrozenDictionary(StringComparer.OrdinalIgnoreCase)(not just the temporaryDictionary), so the frozen instance uses the exact comparer you intend. - Store it in a
static readonlyfield or Singleton DI service so the construction cost is paid once for the lifetime of the application.
When NOT to use FrozenDictionary
- Per-request or short-lived collections: If you construct a dictionary inside an HTTP endpoint, read two keys, and discard it,
ToFrozenDictionary()will be slower thannew Dictionary<K, V>()because its upfront analysis cost outweighs a handful of lookups. - Untrusted user-supplied keys: As Microsoft Learn’s
FrozenDictionarydocumentation explicitly warns, only initializeFrozenDictionarywith trusted keys because key details affect construction time. - Collections that change every few seconds: If items are added or removed frequently at runtime, use
ConcurrentDictionary<K, V>orImmutableDictionary<K, V>instead.
For related .NET performance and API patterns, see System.Text.Json source generation in C# and .NET and using PeriodicTimer for background loops.
Common mistakes
- Calling
.ToFrozenDictionary()on every method invocation. Measure or inspect call sites—frozen collections belong instatic readonlyfields, startup configuration caches, or long-lived singletons. - Forgetting to pass the
IEqualityComparer<TKey>toToFrozenDictionary(comparer). Creating a temporary case-insensitiveDictionaryand calling.ToFrozenDictionary()with no arguments resets the frozen dictionary to the default case-sensitive comparer! - Expecting mutation helpers like
WithAdded(...). UnlikeImmutableDictionary,FrozenDictionaryis intentionally frozen—if data refreshes occasionally, rebuild a newFrozenDictionaryatomically in a background refresh and swap the reference.
Why this matters
Small lookup tables sit on the hot path of routing, validation, serialization, and authorization middleware. Switching static startup maps to FrozenDictionary and FrozenSet is a one-line change that makes hot-path reads faster and guarantees thread-safe immutability across concurrent requests.
My Take
Audit your static readonly Dictionary<...> and HashSet<...> fields in .NET 8+ services: if a collection is populated once at startup from trusted configuration or constants and only ever read afterward, .ToFrozenDictionary() or .ToFrozenSet() is an easy, zero-risk upgrade. Just remember to pass your StringComparer into the .ToFrozen*() call itself.
Conclusion
Use FrozenDictionary<TKey, TValue> and FrozenSet<T> for trusted, long-lived, read-heavy lookup tables initialized once at startup, pass your IEqualityComparer explicitly to ToFrozenDictionary() / ToFrozenSet(), and keep regular Dictionary or ConcurrentDictionary for per-request or frequently updated data.