Skip to content

Commit

Permalink
Retain existing array in RepeatedField.Clear
Browse files Browse the repository at this point in the history
Fixes #7828.

(Also tweaks the comment for Capacity.)
  • Loading branch information
jskeet committed Sep 7, 2022
1 parent 9890369 commit a4fd216
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
12 changes: 12 additions & 0 deletions csharp/src/Google.Protobuf.Test/Collections/RepeatedFieldTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -888,5 +888,17 @@ public void Capacity_Zero()
Assert.DoesNotThrow(() => list.Capacity = 0, "Can set Capacity to 0");
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);
}
}
}
10 changes: 7 additions & 3 deletions csharp/src/Google.Protobuf/Collections/RepeatedField.cs
Original file line number Diff line number Diff line change
Expand Up @@ -279,8 +279,9 @@ public void WriteTo(ref WriteContext ctx, FieldCodec<T> codec)
}

/// <summary>
/// Gets and sets the capacity of the RepeatedField's internal array. WHen set, the internal array is reallocated to the given capacity.
/// <exception cref="ArgumentOutOfRangeException">The new value is less than Count -or- when Count is less than 0.</exception>
/// Gets and sets the capacity of the RepeatedField's internal array.
/// 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>
public int Capacity
{
Expand Down Expand Up @@ -338,7 +339,10 @@ public void Add(T item)
/// </summary>
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;
}

Expand Down

0 comments on commit a4fd216

Please sign in to comment.