Skip to content

IDictionary.GetOrCreate(key) constructs a new TVal on every call, even when the key already exists #170

Closed

Description

@matt-edmondson

What's wrong

Extensions/DictionaryExtensions.cs:20:

public static TVal GetOrCreate<TKey, TVal>(this IDictionary<TKey, TVal> dictionary, TKey key) where TKey : notnull where TVal : notnull, new()
    => GetOrCreate(dictionary, key, new TVal());

new TVal() is passed as an argument, so it runs before the lookup on every call.

Why it matters

The typical use is a loop like Dictionary<string, List<Item>> groups; groups.GetOrCreate(k).Add(x). Every hit allocates a List<Item> and throws it away. Any side effects in TVal's constructor, such as registration, counters or opening a resource, also run on every hit, not only on the miss the method name implies.

The ConcurrentDictionary overload (:71-90) already avoids this by using a factory: GetOrAdd(key, _ => new TVal()). Only the IDictionary overload is eager.

Suggested fix / acceptance criteria

  • Look the key up with TryGetValue first, and construct new TVal() and Add it only on a miss
  • Add a test with a TVal whose constructor increments a static counter, asserting that two calls with the same key construct exactly one instance

Activity

  1. added
    bug
    on Oct 17, 2026
  2. matt-edmondson commented on Oct 18, 2026

    @matt-edmondson
    ContributorAuthor

    Triage

    • Category: Bug
    • Priority: Medium. Each hit wastes an allocation, and any side effects in TVal's constructor run on every call, which contradicts the method's name. The fix is small and local.
    • Area / suggested assignment: DictionaryExtensions.GetOrCreate (the IDictionary overload).
    • Duplicates / in progress: Not a duplicate, and no open PR covers it. Open PR Snapshot AddFrom's items so a collection can add from itself [patch] #168 (AddFrom snapshot) is unrelated.
    • Next step: Use TryGetValue first and construct only on a miss. Add the constructor-counter test.

    Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions