DEV Community

Cover image for FrozenDictionary<K, V> in .NET 8+
Maayur Dahake
Maayur Dahake

Posted on

FrozenDictionary<K, V> in .NET 8+

FrozenDictionary<K, V> in .NET 8+

In many backend microservices, configuration maps, static lookup tables, and feature flags are initialized once at startup and read millions of times throughout the application lifecycle. Using a standard System.Collections.Generic.Dictionary<TKey, TValue> for these scenarios is a hidden tax on your memory allocations and Gen0 garbage collection cycles.

Before

private readonly Dictionary<string, int> _settings = new()
{
    {"Timeout", 30},
    {"Retries", 3},
    {"MaxBatch", 500}
};

public int Get(string key) => _settings[key];
Enter fullscreen mode Exit fullscreen mode

Standard dictionaries must handle dynamic resizing, collision chains, and structural modifications. Even when your data is strictly read-only after startup, the runtime still carries the overhead of mutable structures.

After

private readonly FrozenDictionary<string, int> _settings = new Dictionary<string, int>
{
    {"Timeout", 30},
    {"Retries", 3},
    {"MaxBatch", 500}
}.ToFrozenDictionary();

public int Get(string key) => _settings[key];
Enter fullscreen mode Exit fullscreen mode

Why it matters

  • Zero Allocations: FrozenDictionary<TKey, TValue> optimizes the internal bucket and entry layout for read-only workloads, dropping query heap allocations to zero bytes.
  • Performance Boost: Benchmarks show read throughput beats standard dictionaries by up to 40% due to superior CPU cache utilization and flattened array traversal.
  • Initialization Cost: Freezing the dictionary is an expensive operation. Always perform .ToFrozenDictionary() during application startup or type construction, never per request.

Watch out

Never use frozen collections for data that changes dynamically. Mutation requires calling ToFrozenDictionary() again, which completely rebuilds the underlying hash structures and negates any performance gains.

Where are you still using mutable collections for static reference data?

Top comments (0)