[API Proposal]: Add additional capacity overloads to `ToBuilder` for immutable collections.
- Dominant language
- C#
- Stars
- 18.3k
- Forks
- 5.6k
- PR merge metrics
- PR metrics pending
Description
### 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
```csharp
public Builder ToBuilder(int additionalCapacity);
```
The overload would allocate capacity for the existing elements plus the requested additional capacity.
### API Usage
```csharp
ImmutableArray values = GetValues(); // Count = 10
var builder = values.ToBuilder(additionalCapacity: 8); // capacity = 18
for (int i = 0; i < 8; i++)
{
builder.Add(i);
}
ImmutableArray 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` 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.
Contributor guide
Research direction
The issue names the ToBuilder API and ImmutableArray usage but no source files or tests. Start by locating ToBuilder implementations across the immutable collection types and their capacity-related tests. Done means adding the proposed additionalCapacity overloads without changing parameterless behavior, with coverage for capacity equal to the existing count plus the requested amount.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- csharp
- Domain
- backend-api-design
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Active
- Clarity
- Mostly clear
- Newbie friendliness
- 55/100