[Repo Assist] perf: StringBuilder in CSS readString; AsSpan in JsonStringEncodeTo on .NET 6+#1737
Draft
github-actions[bot] wants to merge 2 commits intomainfrom
Conversation
…n .NET 6+ - HtmlCssSelectors: replace O(n²) string concatenation in readString with StringBuilder accumulator, reducing allocations for CSS selector parsing - JsonValue: use TextWriter.Write(ReadOnlySpan<char>) instead of Substring in JsonStringEncodeTo when targeting .NET 6+ (NETSTANDARD2_0 fallback kept) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
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.
🤖 This PR was created by Repo Assist, an automated AI assistant.
Summary
Two small performance improvements eliminating unnecessary allocations in hot paths:
1.
HtmlCssSelectors.fs—readStringusesStringBuilderThe recursive
readStringfunction was accumulating chars by string concatenation (acc + c.ToString()), allocating a newstringat every step — O(n²) total allocations for a CSS selector token of length n.Fix: replaced the
stringaccumulator with aSystem.Text.StringBuilder, with a thin non-recursivereadStringwrapper keeping all 13 call sites unchanged.2.
JsonValue.fs—JsonStringEncodeTousesAsSpanon .NET 6+JsonStringEncodeTowas usingvalue.Substring(start, len)to flush runs of unescaped characters to aTextWriter, allocating a temporarystring. On .NET 6+ (net8.0 target),TextWriter.Write(ReadOnlySpan<char>)is available and avoids this allocation entirely. Thenetstandard2.0path keepsSubstring.Trade-offs
#if NETSTANDARD2_0 / #elseguard adds a small amount of conditional code; the project already targets bothnetstandard2.0andnet8.0.Test Status
Build and full test suite pass: