Skip to content

Commit cbeb324

Browse files
committed
Pre-size intermediate Dictionary in ToFrozenDictionary
When the source is not already a Dictionary, ToFrozenDictionary builds an intermediate Dictionary to deduplicate keys with last-wins semantics. The previous code used the default-capacity constructor, which paid log2(N) resizes and ~2N redundant rehashes when populating from a known size source such as an array or List. Use ICollection<KeyValuePair>.Count as a capacity hint when available, mirroring the HashSet(IEnumerable, IEqualityComparer) constructor. The ReadOnlySpan overload of FrozenDictionary.Create already pre-sizes, so this brings the IEnumerable path in line with it.
1 parent f288fd5 commit cbeb324

1 file changed

Lines changed: 2 additions & 1 deletion

File tree

src/libraries/System.Collections.Immutable/src/System/Collections/Frozen/FrozenDictionary.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,8 @@ public static FrozenDictionary<TKey, TElement> ToFrozenDictionary<TSource, TKey,
131131
newDictionary = source as Dictionary<TKey, TValue>;
132132
if (newDictionary is null || (newDictionary.Count != 0 && !newDictionary.Comparer.Equals(comparer)))
133133
{
134-
newDictionary = new Dictionary<TKey, TValue>(comparer);
134+
int capacity = source is ICollection<KeyValuePair<TKey, TValue>> collection ? collection.Count : 0;
135+
newDictionary = new Dictionary<TKey, TValue>(capacity, comparer);
135136
foreach (KeyValuePair<TKey, TValue> pair in source)
136137
{
137138
// Dictionary's constructor uses Add, which will throw on duplicates.

0 commit comments

Comments
 (0)