skip to content

In .NET 8 and later, a pricing service freezes its case-insensitive currency table with loaded.ToFrozenDictionary(), and lookups of "usd" now miss; why, and when is freezing worth it?

level: seniorimportance: should knowfreq 40%

answer

  1. which comparer the new dictionary uses
  2. the optional comparer parameter
  3. expensive build, cheap reads
  4. built once, read on every request

basics

~10 s

ToFrozenDictionary uses EqualityComparer<TKey>.Default unless you pass a comparer, so freezing a case-insensitive Dictionary without one rebuilds it case-sensitively. Pass StringComparer.OrdinalIgnoreCase. Freezing pays off for tables built once and read constantly.

solid answer

~40 s

`ToFrozenDictionary(source, comparer = null)` does not inherit the source dictionary's comparer: a null comparer means `EqualityComparer<TKey>.Default`, and when the source `Dictionary<TKey,TValue>` uses a different one it is copied into a new dictionary with the default comparer first. A table built with `StringComparer.OrdinalIgnoreCase` therefore becomes case-sensitive, and `rates["usd"]` throws `KeyNotFoundException`. The fix is `loaded.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase)`. `FrozenDictionary<TKey,TValue>` (`System.Collections.Frozen`, .NET 8) is worth it when a table is **built once, at startup, and read on every request**: the build analyses the keys and picks a specialised implementation, which costs noticeably more than filling a `Dictionary`, and afterwards lookups are typically faster. It has no mutating methods at all, so data that changes means building a new one and swapping the reference.

code

csharp · 25 lines
csharp
using System.Collections.Frozen;
using System.Globalization;

CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;

var loaded = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase)
{
    ["EUR"] = 1.00m, ["USD"] = 1.08m, ["GBP"] = 0.85m,
    ["JPY"] = 162.4m, ["CHF"] = 0.95m, ["SEK"] = 11.5m,
};

FrozenDictionary<string, decimal> lost = loaded.ToFrozenDictionary();
Console.WriteLine(lost.ContainsKey("usd"));          // False: rebuilt with the default comparer

FrozenDictionary<string, decimal> rates =
    loaded.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);
Console.WriteLine(rates["usd"]);                     // 1.08
Console.WriteLine(rates.GetType().Name);             // the concrete strategy picked for these keys

loaded["NOK"] = 11.7m;                               // a later change to the source
Console.WriteLine(rates.ContainsKey("NOK"));         // False: the frozen copy never changes

IDictionary<string, decimal> asDictionary = rates;
try { asDictionary.Add("NOK", 11.7m); }
catch (NotSupportedException) { Console.WriteLine("NotSupportedException"); }

go deeper

for a junior

Recall that a frozen dictionary is built once from existing data, can never change, and is meant for fast lookups.

for a middle

Explain that freezing analyses the keys to pick a lookup strategy, so building costs more and reading costs less.

for a senior

Catch the dropped comparer and the last-wins duplicates, and reserve freezing for startup-built tables that are swapped as a whole on change.

for a principal

Decide where frozen collections become the default for read-mostly configuration, and set the rule that every freeze passes its comparer explicitly.

## What went wrong The service loads its currency rates into `new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase)` so that "usd", "USD" and "Usd" all match. At startup it freezes the table: ```csharp FrozenDictionary<string, decimal> rates = loaded.ToFrozenDictionary(); ``` Now `rates["usd"]` throws `KeyNotFoundException`, while `rates["USD"]` works. The signature explains it: `ToFrozenDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source, IEqualityComparer<TKey>? comparer = null)`. The parameter is documented as the comparer for the new dictionary, and **null means `EqualityComparer<TKey>.Default`**, not "whatever the source used". In the source, when the input is a `Dictionary<TKey,TValue>` whose comparer differs from the requested one, it is first copied into a new `Dictionary<TKey,TValue>` with the requested comparer, and that copy is frozen. For strings the default comparer is ordinal and case-sensitive. The fix is one argument: `loaded.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase)`. The same rule applies to `ToFrozenSet(comparer)`. Two other build details from the source are worth knowing: - Duplicate keys in a sequence of pairs do not throw: **the last one wins**, unlike `Enumerable.ToDictionary`, which throws `ArgumentException`. - The `ToFrozenDictionary(keySelector, ...)` overloads build an ordinary `Dictionary` first and then freeze it, so the build allocates both. ## What freezing buys `FrozenDictionary<TKey,TValue>` and `FrozenSet<T>` were added in .NET 8. They are immutable, and the source describes the trade plainly: a relatively high cost to create, in exchange for excellent lookup performance, ideal for a dictionary created once, perhaps at startup, and used for the rest of the application's life. The build is expensive because it **chooses an implementation for the actual keys**. On .NET 10 the source picks among these: | Keys | What the build may pick | |---|---| | Value types with the default comparer, e.g. `int` or an enum | an array indexed by key for densely packed integral keys, a small scan for up to 10 keys (sorted for primitive keys), or a hash table that reuses `int` keys as their own hashes | | `string` with the default, `Ordinal` or `OrdinalIgnoreCase` comparer | buckets by string length, or hashing only the few characters that tell the keys apart | | Other key types or comparers, up to 4 entries | a plain linear scan | | Everything else | a general frozen hash table | The concrete class name, such as the one the code example prints, is an implementation detail that can change between releases; the point is that lookups are tuned to the keys you gave it. The source also notes that a frozen dictionary should only be built from **trusted keys**, because the keys affect construction time. After the build: - `TryGetValue`, `ContainsKey` and the indexer are typically faster than on a `Dictionary<TKey,TValue>` with the same keys. - The indexer returns `ref readonly TValue`, and `GetValueRefOrNullRef` avoids copying large struct values. - `Keys` and `Values` are exposed as `ImmutableArray<TKey>` and `ImmutableArray<TValue>`. - Reads need no locking, because nothing can ever change. ## What it costs 1. **No mutation, ever.** There is no `Add`, `Remove` or `SetItem`; the `IDictionary<TKey,TValue>` members throw `NotSupportedException`. Changes to the source after freezing are not seen. 2. **A changing table means a rebuild.** When an admin edits the rates, the service builds a new frozen dictionary and replaces the field that readers use. That is fine for edits a few times a day; for frequent writes the full rebuild cost dominates, and `ImmutableDictionary<TKey,TValue>.SetItem` or a locked `Dictionary` fits better. 3. **Build time at startup.** For a large table built once per process, the extra build time is paid once and amortised over millions of lookups; for a dictionary built per request and read three times, freezing is pure overhead. ## When to choose it - Configuration, currency tables, feature-flag names, routing keys and allow-lists loaded at startup: **freeze them**. - A cache filled lazily while the process runs: not frozen; it needs inserts. - Short-lived dictionaries: a plain `Dictionary<TKey,TValue>`. Before adopting it for a large table, measure rather than assume. Wrap the build in `GC.GetAllocatedBytesForCurrentThread()` calls and time the startup path: in one .NET 10 run with 50,000 string keys, the `keySelector` overload of `ToFrozenDictionary` allocated several times what `ToDictionary` did for the same keys, partly because it builds a `Dictionary` first. That cost is acceptable once per process and not acceptable on a request path. Whatever the choice, pass the comparer explicitly when freezing; it is the one argument the frozen collection cannot recover from its source.

  • How should the service publish a rebuilt frozen table when an admin edits rates?
    Build the new `FrozenDictionary<TKey,TValue>` off to the side, then replace the field readers use in one reference assignment, for example with `Volatile.Write` or `Interlocked.Exchange`. Readers that already took the old reference finish against a complete, consistent table; new requests see the new one. Nothing is ever half-updated.
  • What happens on ToFrozenDictionary when the input pairs contain the same key twice?
    The last pair wins, silently. The source copies pairs into a dictionary using the indexer rather than `Add`, so a duplicate overwrites the earlier value. `Enumerable.ToDictionary` would throw `ArgumentException` instead, so a data error that used to fail fast can slip through.
  • Is a FrozenDictionary<TKey,TValue> worth building for a dictionary used once per request?
    No. The build analyses all the keys and allocates more than filling a `Dictionary<TKey,TValue>`, and that cost is only recovered over many lookups. For a short-lived dictionary read a few times, a plain `Dictionary` is cheaper overall.

  • ToFrozenDictionary keeps the source dictionary's comparer automatically
  • A FrozenDictionary is cheaper to build than a Dictionary
  • You can add entries to a FrozenDictionary through IDictionary<TKey,TValue>
  • Freezing a per-request dictionary makes the request faster
  • Changes to the source dictionary show up in the frozen copy
  • Duplicate keys make ToFrozenDictionary throw ArgumentException

Assumes .NET 10; FrozenDictionary<TKey,TValue> and FrozenSet<T> were added in .NET 8 in System.Collections.Frozen.