Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

Commit 391be01

Browse files
authored
Adding EnsureCapacity implementation for Dictionary (#15729)
Adding EnsureCapacity implementation for Dictionary
1 parent 2efb857 commit 391be01

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

src/mscorlib/shared/System/Collections/Generic/Dictionary.cs

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -373,7 +373,7 @@ private int FindEntry(TKey key)
373373
return -1;
374374
}
375375

376-
private void Initialize(int capacity)
376+
private int Initialize(int capacity)
377377
{
378378
int size = HashHelpers.GetPrime(capacity);
379379
int[] buckets = new int[size];
@@ -385,6 +385,8 @@ private void Initialize(int capacity)
385385
_freeList = -1;
386386
_buckets = buckets;
387387
_entries = new Entry[size];
388+
389+
return size;
388390
}
389391

390392
private bool TryInsert(TKey key, TValue value, InsertionBehavior behavior)
@@ -759,6 +761,22 @@ IEnumerator IEnumerable.GetEnumerator()
759761
return new Enumerator(this, Enumerator.KeyValuePair);
760762
}
761763

764+
/// <summary>
765+
/// Ensures that the dictionary can hold up to 'capacity' entries without any further expansion of its backing storage
766+
/// </summary>
767+
public int EnsureCapacity(int capacity)
768+
{
769+
if (capacity < 0)
770+
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity);
771+
if (_entries != null && _entries.Length >= capacity)
772+
return _entries.Length;
773+
if (_buckets == null)
774+
return Initialize(capacity);
775+
int newSize = HashHelpers.GetPrime(capacity);
776+
Resize(newSize, forceNewHashCodes: false);
777+
return newSize;
778+
}
779+
762780
bool ICollection.IsSynchronized
763781
{
764782
get { return false; }

0 commit comments

Comments
 (0)