Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stored the initial capacity of the ConcurrentDictionary for correctly sizing the backing array after clearing the collection. #108065

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@ public class ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDi
/// extra branch when using a custom comparer with a reference type key.
/// </remarks>
private readonly bool _comparerIsDefaultForClasses;
/// <summary>The initial size of the _buckets array.</summary>
/// <remarks>
/// We store this to retain the initially specified growing behavior of the _buckets array even after clearing the collection.
/// </remarks>
private readonly int _initialCapacity;

/// <summary>The default capacity, i.e. the initial # of buckets.</summary>
/// <remarks>
Expand Down Expand Up @@ -220,6 +225,7 @@ internal ConcurrentDictionary(int concurrencyLevel, int capacity, bool growLockA

_tables = new Tables(buckets, locks, countPerLock, comparer);
_growLockArray = growLockArray;
_initialCapacity = capacity;
_budget = buckets.Length / locks.Length;
}

Expand Down Expand Up @@ -716,7 +722,7 @@ public void Clear()
}

Tables tables = _tables;
var newTables = new Tables(new VolatileNode[HashHelpers.GetPrime(DefaultCapacity)], tables._locks, new int[tables._countPerLock.Length], tables._comparer);
var newTables = new Tables(new VolatileNode[HashHelpers.GetPrime(_initialCapacity)], tables._locks, new int[tables._countPerLock.Length], tables._comparer);
_tables = newTables;
_budget = Math.Max(1, newTables._buckets.Length / newTables._locks.Length);
}
Expand Down
Loading