Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Retain existing array in RepeatedField.Clear #10508

Merged
merged 1 commit into from
Sep 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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