You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
IDictionary.GetOrCreate(key) constructs a new TVal on every call, even when the key already exists #170
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
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).
Activity
matt-edmondson commentedon Oct 18, 2026
Triage
TVal's constructor run on every call, which contradicts the method's name. The fix is small and local.DictionaryExtensions.GetOrCreate(theIDictionaryoverload).AddFromsnapshot) is unrelated.TryGetValuefirst and construct only on a miss. Add the constructor-counter test.Generated by Claude Code