skip to content

A hot C# loop updates a Dictionary<TKey,TValue> with ContainsKey and then the indexer — how do you cut the repeated lookups, and what makes CollectionsMarshal.GetValueRefOrAddDefault risky?

level: seniorimportance: should knowfreq 32%

answer

  1. count the hash computations
  2. analyzer rules for guarded lookups
  3. a ref into the value slot
  4. what a resize does to it

basics

~20 s

ContainsKey plus the indexer hashes the key twice, three times for read-modify-write. Use TryGetValue or TryAdd for one lookup, or CollectionsMarshal.GetValueRefOrAddDefault to update in place, but never add or remove entries while holding that ref.

solid answer

~50 s

`ContainsKey`, the getter and the setter each hash the key and walk a bucket chain, so `if (d.ContainsKey(k)) d[k] = d[k] + 1; else d[k] = 1;` pays three lookups on a hit. `TryGetValue` folds the guarded read into one (CA1854 flags the pattern) and `TryAdd` replaces `ContainsKey` plus `Add` (CA1864). A counter still needs a read and a write, so on a hot path `CollectionsMarshal.GetValueRefOrAddDefault(dict, key, out bool exists)` returns a `ref` to the value slot, inserting `default` when missing, and `count++` through it is one lookup. The ref points into the dictionary's internal entries array, and the documented rule is that items should not be added or removed while it is in use: a resize moves entries to a new array, so a write through the old ref is lost, and a removed slot can be handed to another key.

code

csharp · 21 lines
csharp
using System.Runtime.InteropServices;

var scans = new Dictionary<WarehouseBin, int>();
WarehouseBin[] feed = [new("A", 1, 4), new("B", 2, 1), new("A", 1, 4)];

foreach (var bin in feed)
{
    // One hash-and-probe: adds default(int) when missing, returns a ref to the value slot.
    ref int count = ref CollectionsMarshal.GetValueRefOrAddDefault(scans, bin, out bool exists);
    count++;
}
foreach (var (bin, n) in scans) Console.WriteLine($"{bin.Aisle}-{bin.Shelf}-{bin.Slot}: {n}");

// The hazard: keep the ref while the dictionary grows.
var tally = new Dictionary<int, int>();
ref int first = ref CollectionsMarshal.GetValueRefOrAddDefault(tally, 0, out _);
for (int i = 1; i < 100; i++) tally.Add(i, i);   // forces a resize: new entries array
first = 42;                                       // writes into the old, abandoned array
Console.WriteLine(tally[0]);                      // 0, not 42

readonly record struct WarehouseBin(string Aisle, int Shelf, int Slot);

go deeper

for a junior

Know that ContainsKey followed by the indexer looks the key up twice, and that TryGetValue does the same job with one lookup.

for a middle

Explain what each lookup costs, hashing through the comparer and walking a bucket chain, and which analyzer rules flag the guarded ContainsKey patterns.

for a senior

Use GetValueRefOrAddDefault on a measured hot path and state its rule without prompting: no adds or removes while the ref is alive, because a resize or a reused slot makes the ref stale silently.

for a principal

Treat CollectionsMarshal as an opt-in for profiled hotspots with a comment and a test, not a team idiom; the Try methods remain the default that reviewers should expect.

## What one lookup costs A `Dictionary<TKey,TValue>` lookup is not free. Each call that takes a key, `ContainsKey`, the indexer getter, the indexer setter, `Add`, `TryAdd`, `TryGetValue`, runs the same internal search: 1. Compute the key's hash through the dictionary's `IEqualityComparer<TKey>`, or the key's own `GetHashCode` for a value type with the default comparer. 2. Map the hash to a bucket. 3. Walk that bucket's chain, calling `Equals` on each candidate with a matching hash code. For a key such as `record struct WarehouseBin(string Aisle, int Shelf, int Slot)`, step 1 hashes a string and two integers, so the hash and equality calls dominate. The guarded counter pattern repeats the search three times on a hit: ```csharp if (scans.ContainsKey(bin)) scans[bin] = scans[bin] + 1; // search, search, search else scans[bin] = 1; // search, search on a miss ``` ## One counter written three ways The same scan counter shows how the lookup count falls: 1. **Guarded**: `if (scans.ContainsKey(bin)) scans[bin] = scans[bin] + 1; else scans[bin] = 1;` costs three searches when the bin is known and two when it is new. 2. **TryGetValue then set**: `scans.TryGetValue(bin, out int n); scans[bin] = n + 1;` costs two searches every time, because `TryGetValue` leaves `n` at `0` for a new bin and the setter searches again to store the result. 3. **Ref**: `CollectionsMarshal.GetValueRefOrAddDefault(scans, bin, out _)++` costs one search, because the increment happens in the slot the search found. Version 2 is what most teams should write; version 3 is for the loop a profiler points at. ## The one-lookup replacements | Pattern | Replace with | Analyzer | |---|---|---| | `ContainsKey` then the getter | `TryGetValue(key, out value)` | **CA1854** | | `ContainsKey` then `Add` | `TryAdd(key, value)` | **CA1864** | | `TryGetValue` then `Remove` | `Remove(key, out value)` | none | | read, change, write back a value type | `CollectionsMarshal.GetValueRefOrAddDefault` | none | The first three are safe everyday code. `TryGetValue` followed by the setter is still two searches, which is why counters and accumulators look for something more. ## Updating in place through a ref `System.Runtime.InteropServices.CollectionsMarshal.GetValueRefOrAddDefault<TKey,TValue>(Dictionary<TKey,TValue> dictionary, TKey key, out bool exists)` searches once. If the key exists it returns a `ref TValue?` to the stored value; if not, it inserts the key with `default(TValue)` and returns a ref to that new slot, with `exists` telling you which happened. `ref int count = ref CollectionsMarshal.GetValueRefOrAddDefault(scans, bin, out _); count++;` is a complete counter with one hash. Its sibling `GetValueRefOrNullRef` returns a null ref instead of inserting, which you test with `Unsafe.IsNullRef`, for update-only paths. The gain is largest when `TValue` is a value type, such as an `int` counter or a struct of totals, because the normal path must copy the value out and write it back. When `TValue` is a class, `TryGetValue` already hands you the object reference and you can mutate its fields with one lookup. ## The rule that makes it risky The ref points directly into the dictionary's private entries array. The XML docs on both methods say items should not be added to or removed from the dictionary while the ref is in use, and the reasons are mechanical: - **Resize.** When an insertion exceeds capacity, the dictionary allocates a larger entries array and copies into it. A ref taken before the resize still points into the old array, so a write through it lands somewhere the dictionary never reads again. No exception is thrown; the update is silently lost. - **Removal.** `Remove` puts the slot on a free list, and the next insertion reuses it for a different key, so an old ref can end up aliasing another key's value. - **Threads.** The ref adds no synchronization; concurrent writers corrupt a plain `Dictionary<TKey,TValue>` with or without it. The example below shows the resize case: a ref to key `0`, ninety-nine more insertions, a write of `42` through the ref, and `tally[0]` still reads `0`. ## When to reach for it - Use `TryGetValue`, `TryAdd` and `Remove(key, out value)` everywhere; they remove the redundant searches without any new rules. - Use `GetValueRefOrAddDefault` only where a profile shows the dictionary update is hot and the value is a value type. - Keep the ref's lifetime to a single statement or a short block with no other calls into the same dictionary in between. - Leave a comment at the call site naming the rule, because the next editor who adds an `Add` inside that block will not get a compiler error.

  • When is CollectionsMarshal.GetValueRefOrNullRef the better call?
    On an update-only path, where a missing key must not create an entry. It returns a ref to the value or a null ref, which you test with `Unsafe.IsNullRef`, so decrementing stock for a known bin never inserts a bin that came from a typo. The same lifetime rule applies: no adds or removes while the ref is alive.
  • Is the ref trick worth it when TValue is a class?
    Rarely. `TryGetValue` returns the object reference in one lookup, and you mutate the object's fields through it; nothing needs writing back into the dictionary. The ref pays off for value types, where the usual path copies the value out and stores it back with a second search.
  • Why does the stale ref not throw anything?
    A ref is a raw managed pointer, not an enumerator, so it carries no version stamp to check. The old entries array stays alive while the ref points into it, so writes succeed; they just modify memory the dictionary no longer reads. That is why the bug shows up as a lost update, not a crash.

  • ContainsKey followed by the indexer is a single hash lookup.
  • TryGetValue followed by the indexer setter updates a counter with one lookup.
  • The ref from GetValueRefOrAddDefault stays valid after more entries are added.
  • A stale dictionary ref throws InvalidOperationException like a modified enumerator.
  • GetValueRefOrAddDefault makes concurrent updates to a Dictionary safe.