diff --git a/src/Compilers/Core/CodeAnalysisTest/Collections/List/SegmentedList.Generic.Tests.Capacity.cs b/src/Compilers/Core/CodeAnalysisTest/Collections/List/SegmentedList.Generic.Tests.Capacity.cs index ec2347a570b8e..6df220121fb62 100644 --- a/src/Compilers/Core/CodeAnalysisTest/Collections/List/SegmentedList.Generic.Tests.Capacity.cs +++ b/src/Compilers/Core/CodeAnalysisTest/Collections/List/SegmentedList.Generic.Tests.Capacity.cs @@ -140,5 +140,18 @@ public void EnsureCapacity_MatchesSizeWithLargeCapacityRequest(int segmentCount) Assert.Equal(expectedCapacity, list.Capacity); } + + [Fact] + public void EnsureCapacity_InitialCapacitySlightlyMoreThanHalfSegmentSizeGrowsToFullSegmentSize() + { + var elementCount = SegmentedArray.TestAccessor.SegmentSize / 2 + 1; + var list = new SegmentedList(elementCount); + + Assert.Equal(elementCount, list.Capacity); + + list.EnsureCapacity(elementCount + 1); + + Assert.Equal(SegmentedArray.TestAccessor.SegmentSize, list.Capacity); + } } } diff --git a/src/Dependencies/Collections/SegmentedList`1.cs b/src/Dependencies/Collections/SegmentedList`1.cs index f00c76a6897df..9e6a45a8ede98 100644 --- a/src/Dependencies/Collections/SegmentedList`1.cs +++ b/src/Dependencies/Collections/SegmentedList`1.cs @@ -520,6 +520,11 @@ internal void Grow(int capacity) // should be DefaultCapacity. Otherwise, the new capacity should be double the current array size. newCapacity = _items.Length == 0 ? DefaultCapacity : _items.Length * 2; } + else if (_items.Length < SegmentedArrayHelper.GetSegmentSize()) + { + // There is only a single segment that is over half full. Increase it to a full segment. + newCapacity = SegmentedArrayHelper.GetSegmentSize(); + } else { // If the last segment is fully sized, increase the number of segments by the desired growth rate