Simplify StringBuilder indexer to reuse FindChunkForIndex#130554
Merged
tannergooding merged 1 commit intoJul 13, 2026
Conversation
The get/set indexers open-coded a chunk walk that did two comparisons per hop and traversed the entire chunk list to validate an out-of-range index. Hoist a single `(uint)index >= (uint)Length` bounds check up front so the out-of-range path is O(1) and each hop of the walk is a single comparison, then reuse the existing `FindChunkForIndex` helper for the traversal. Route the throws through `ThrowHelper` so the property bodies stay small enough to inline. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Member
Author
|
@EgorBot -linux_amd -osx_arm64 using System.Text;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
BenchmarkSwitcher.FromAssembly(typeof(Bench).Assembly).Run(args);
public class Bench
{
[Params(8, 64, 512, 4096)]
public int Length { get; set; }
private StringBuilder _presized = null!; // single chunk
private StringBuilder _grown = null!; // many chunks via front-inserts
[GlobalSetup]
public void Setup()
{
_presized = new StringBuilder(Length);
for (int i = 0; i < Length; i++) _presized.Append((char)('a' + (i % 26)));
_grown = new StringBuilder();
for (int i = 0; i < Length; i++) _grown.Insert(0, (char)('a' + (i % 26)));
}
[Benchmark]
public int Sum_Presized()
{
StringBuilder sb = _presized;
int sum = 0;
for (int i = 0; i < sb.Length; i++) sum += sb[i];
return sum;
}
[Benchmark]
public int Sum_Grown()
{
StringBuilder sb = _grown;
int sum = 0;
for (int i = 0; i < sb.Length; i++) sum += sb[i];
return sum;
}
[Benchmark]
public void Set_Grown()
{
StringBuilder sb = _grown;
for (int i = 0; i < sb.Length; i++) sb[i] = 'x';
}
}Note This comment was drafted by GitHub Copilot on my behalf. |
Contributor
|
Tagging subscribers to this area: @dotnet/area-system-runtime |
Contributor
There was a problem hiding this comment.
Pull request overview
This PR refactors StringBuilder’s char this[int index] indexer to do a single up-front bounds check against Length, then reuse the existing FindChunkForIndex helper to locate the backing chunk, and route exception creation through ThrowHelper. This keeps the indexer’s semantics the same while reducing per-hop work and keeping the getter/setter bodies smaller.
Changes:
- Replace open-coded backward chunk walk in the indexer with
FindChunkForIndex(index). - Add a single
(uint)index >= (uint)Lengthbounds check to cover negative and too-large indices without an O(chunks) validation path. - Use
ThrowHelperforIndexOutOfRangeException(getter) andArgumentOutOfRangeExceptionwith theindexparameter andSR.ArgumentOutOfRange_IndexMustBeLessresource (setter).
Show a summary per file
| File | Description |
|---|---|
| src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs | Simplifies indexer get/set by hoisting bounds checks, reusing FindChunkForIndex, and centralizing throws via ThrowHelper. |
Copilot's findings
- Files reviewed: 1/1 changed files
- Comments generated: 0
eiriktsarpalis
approved these changes
Jul 13, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Indexing into a
StringBuilderis O(number of chunks) by nature (see #64545), but the get/set indexer implementations were also doing more per-hop work than necessary:indexInBlock >= 0andindexInBlock >= m_ChunkLength).m_ChunkPrevious == null, i.e. the error path was itself O(chunks).new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLess)inline, bloating the property body and blocking inlining.Since chunks tile
[0, Length)with no gaps andLengthis O(1), a single up-front(uint)index >= (uint)Lengthcheck is sufficient to validate the index (covering both negative and too-large in one unsigned compare). After that, the chunk containing the index is exactly what the existingFindChunkForIndexhelper returns, so the walk becomes a single comparison per hop and the helper is reused rather than open-coded a third time. The throws are routed throughThrowHelperso the property bodies stay small enough to inline.No behavior change: the getter still throws
IndexOutOfRangeExceptionand the setter still throwsArgumentOutOfRangeExceptionwith the sameindexparameter name and resource.Benchmark
Both indexer variants modeled side-by-side over a faithful chunk structure (
_Start= index near 0 / max hops,_End= index in the head chunk / 0 hops,ChunkCount= number of chunks). .NET 10.0.9, X64 RyuJIT AVX2:(ns, mean; zero allocations either way.)
Highlights:
FindChunkForIndexinlines into the property on modern RyuJIT.StdDev3.37ns → 0.03ns; the old shape was multimodal).I've left
FindChunkForIndexitself unchanged — it's already a minimal backward pointer-chase, and the remaining cost on deep walks is memory-latency-bound traversal, which is a growth-algorithm concern out of scope for this change.Note
This PR description was drafted by GitHub Copilot on my behalf.