[API Proposal]: Add additional capacity overloads to `ToBuilder` for immutable collections.
Background and motivation
The parameterless ToBuilder() APIs initialize the builder based on the current collection size.
When a caller expects to add elements, there is currently no way to specify the additional capacity needed. For capacity-based builders, this can cause overheads like resize-and-copy operations as elements are added.
An explicit overload allows callers to request additional capacity without changing existing behavior.
This proposal is related to #1000.
API Proposal
public Builder ToBuilder(int additionalCapacity);
The overload would allocate capacity for the existing elements plus the requested additional capacity.
API Usage
ImmutableArray<int> values = GetValues(); // Count = 10
var builder = values.ToBuilder(additionalCapacity: 8); // capacity = 18
for (int i = 0; i < 8; i++)
{
builder.Add(i);
}
ImmutableArray<int> result = builder.MoveToImmutable();
Alternative Designs
One alternative is to change the parameterless ToBuilder() implementation to allocate additional capacity by default.
This was investigated for ImmutableArray<T> using BenchmarkDotNet across different collection sizes and numbers of subsequent Add() operations. The results did not show a consistent performance improvement, and changing the default could regress scenarios where the additional capacity is not needed.
The proposed overload avoids changing the existing behavior while allowing callers that know their expected growth to request additional capacity explicitly.
Risks
There are no breaking changes to existing APIs. The parameterless ToBuilder() behavior remains unchanged, so existing callers are not affected.
The main consideration is the additional memory allocated when callers request capacity that is not ultimately used. This is explicitly controlled by the caller through the additionalCapacity parameter.
Tagging subscribers to this area: @dotnet/area-system-collections See info in area-owners.md if you want to be subscribed.
When the added elements is known, it's much more optimal to avoid the usage of Builder totally, and use AddRange(ReadOnlySpan) instead:
ImmutableArray<int> values = GetValues(); // Count = 10
var buffer = stackalloc int[8];
for (int i = 0; i < 8; i++)
{
buffer[i] = i;
}
ImmutableArray<int> result = values.AddRange(buffer);
It's also less risk for misusing. For example, the sample in OP is suboptimal, because it uses ToImmutable() instead of MoveToImmutable().
I agree that AddRange(ReadOnlySpan<T>) is preferable when the operation is simply “take the existing immutable array and append N already-materialized elements”.
However, when the caller already needs a Builder for multiple mutations, knowing the expected growth is still useful.
For example, consider applying a batch of edits where the number of inserted or appended elements is known up front:
var additionalCapacity = edits.Count(e =>
e.Kind is EditKind.Insert or EditKind.Add);
var builder = values.ToBuilder(additionalCapacity);
foreach (var edit in edits)
{
switch (edit.Kind)
{
case EditKind.Insert:
builder.Insert(edit.Index, edit.Value);
break;
case EditKind.Replace:
builder[edit.Index] = edit.Value;
break;
case EditKind.Remove:
builder.RemoveAt(edit.Index);
break;
case EditKind.Add:
builder.Add(edit.Value);
break;
}
}
return builder.MoveToImmutable();
AddRange does not represent this workload, since the additions are interleaved with inserts, replacements, and removals. In this case, the Builder is needed as the mutable representation throughout the operation.
More generally, when a caller already needs to perform multiple individual mutations on a Builder and can estimate the amount of growth in advance, allowing that expected growth to be specified up front can avoid capacity growth during the mutation phase.
I’ve updated the example to use MoveToImmutable(); ToImmutable() was only used in the original example for brevity.
Right, AddRange only works if you already have a "slice" to add.
If you know you need to add n items, but its > 1 separate items, then you need something like the ToBuilder(additionalCapacity: n) approach -- and there are workarounds, you can do this already, its just not nearly as convenient.
Without ToBuilder(additionalCapacity), we would need to use ImmutableArray.CreateBuilder<T>(initialCapacity) and AddRange, as shown below. That is certainly a bit of a hassle.
ImmutableArray<int> values = GetValues(); // Count = 10
int additionalCapacity = 8;
var builder = ImmutableArray.CreateBuilder<int>(values.Length + additionalCapacity);
builder.AddRange(values);
// Add exactly `additionalCapacity` elements
ImmutableArray<int> result = builder.MoveToImmutable();
I'm anxious about squatting on ToBuilder(int) for the int to be additional capacity. The approach @prozolic shows is a bit of a hassle, but it's pretty expressive in my opinion.
We could consider making the intent explicit in the API name, e.g. ToBuilderWithAdditionalCapacity(int), ToBuilderWithAddCapacity(int).
Alternatively, we could keep ToBuilder(int) and rely on the named argument for discoverability: ToBuilder(additionalCapacity: 8).
@jeffhandley, what other signatures would you expect it to be?
Notably, this is somewhat an existing pattern found in other collection APIs (TrimExcess is one example); however its typically an exact capacity rather than an additional capacity for the integer value.