Merge pull request #10508 from jskeet/clear-retain

Retain existing array in RepeatedField.Clear
pull/10515/head
Matt Fowles Kulukundis 3 years ago committed by GitHub
commit ad6cd54b1e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  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