Retain existing array in RepeatedField.Clear

Fixes #7828.

(Also tweaks the comment for Capacity.)
pull/10508/head
Jon Skeet 2 years ago
parent 9890369bc3
commit a4fd216186
  1. 12
      csharp/src/Google.Protobuf.Test/Collections/RepeatedFieldTest.cs
  2. 10
      csharp/src/Google.Protobuf/Collections/RepeatedField.cs

@ -888,5 +888,17 @@ namespace Google.Protobuf.Collections
Assert.DoesNotThrow(() => list.Capacity = 0, "Can set Capacity to 0"); Assert.DoesNotThrow(() => list.Capacity = 0, "Can set Capacity to 0");
Assert.AreEqual(0, list.Capacity); Assert.AreEqual(0, list.Capacity);
} }
[Test]
public void Clear_CapacityUnaffected()
{
var list = new RepeatedField<int> { 1 };
Assert.AreEqual(1, list.Count);
Assert.AreEqual(8, list.Capacity);
list.Clear();
Assert.AreEqual(0, list.Count);
Assert.AreEqual(8, list.Capacity);
}
} }
} }

@ -279,8 +279,9 @@ namespace Google.Protobuf.Collections
} }
/// <summary> /// <summary>
/// Gets and sets the capacity of the RepeatedField's internal array. WHen set, the internal array is reallocated to the given capacity. /// Gets and sets the capacity of the RepeatedField's internal array.
/// <exception cref="ArgumentOutOfRangeException">The new value is less than Count -or- when Count is less than 0.</exception> /// When set, the internal array is reallocated to the given capacity.
/// <exception cref="ArgumentOutOfRangeException">The new value is less than <see cref="Count"/>.</exception>
/// </summary> /// </summary>
public int Capacity public int Capacity
{ {
@ -338,7 +339,10 @@ namespace Google.Protobuf.Collections
/// </summary> /// </summary>
public void Clear() public void Clear()
{ {
array = EmptyArray; // Clear the content of the array (so that any objects it referred to can be garbage collected)
// but keep the capacity the same. This allows large repeated fields to be reused without
// array reallocation.
Array.Clear(array, 0, count);
count = 0; count = 0;
} }

Loading…
Cancel
Save