Repository navigation
Only materialize the requested range in StringBuilder.Append(StringBuilder, int, int) - #698
Merged
Merged
Conversation
This was referenced Oct 12, 2026
This was referenced Oct 14, 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.
The
StringBuilder.Append(StringBuilder, int, int)polyfill (active on .NET Framework / netstandard2.0) ended withtarget.Append(value.ToString(), startIndex, count), materializing the entire source builder as a string to append a slice of it. Appending small ranges out of a large builder allocated and copied the whole source each time.It now appends
value.ToString(startIndex, count), which only copies the requested range.string'sAppend(string, int, int)used to do the range check, so that check is made explicitly first (startIndex > value.Length - countthrowsArgumentOutOfRangeExceptionforstartIndex, the same exception and parameter name as before). The earlier checks, the null handling and thecount == 0early return are untouched.Measurements
net48, Release, x64, best of 3, 1,000 appends of a 16 char range out of a 1,000,000 char source builder:
(Before also allocated a 2 MB string per call.)
Tests
Added to
PolyfillTests_StringBuilder.cs:StringBuilder_Append_StringBuilder_Ranges: start, middle, end, whole and empty ranges, checking the returned instance and that the source is unchangedStringBuilder_Append_StringBuilder_MultiChunkSource: ranges of a 30,000 char source built from many small appends, including ones spanning chunk boundariesStringBuilder_Append_StringBuilder_Self(appending a builder to itself)StringBuilder_Append_StringBuilder_OutOfRange: ranges past the end, includingint.MaxValuefor either argumentStringBuilder_Append_StringBuilder_Null