Replace String Concatenation with ValueStringBuilder
for Performance Optimization
#1423
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.
🔧 Replace String Concatenation with
ValueStringBuilder
for Performance OptimizationSummary
This PR refactors string concatenation logic in the library to use a custom
ValueStringBuilder
implementation backed byArrayPool<char>.Shared
. This change improves performance by reducing memory allocations and GC pressure, especially in hot paths or high-throughput scenarios.📌 Why Avoid String Concatenation?
String concatenation using the
+
operator orstring.Concat
creates a new string instance for each operation, leading to:✅ Why Use StringBuilder?
StringBuilder
is a mutable buffer that allows efficient appending of strings without creating intermediate string instances. It is ideal for scenarios involving:However,
StringBuilder
itself has limitations:🚀 Why
ValueStringBuilder
withArrayPool<char>.Shared
?To further optimize performance, this PR introduces a ValueStringBuilder that:
Span<char>
)ArrayPool<char>.Shared
for larger buffersThis approach is inspired by internal .NET implementations (e.g.,
System.Text.Json
, Roslyn) and is particularly effective in performance-critical code paths.🧩 Collaborative String Composition with ToString(ref ValueStringBuilder)
This implementation also introduces
ToString(ref ValueStringBuilder)
methods to enable collaborative string composition. Instead of each component returning a fully-formed string viaToString()
, which would then be copied into a larger result, each component writes directly into a sharedValueStringBuilder
.Benefits:
Example:
And in the parent object:
NOTE: This does not replace all occurrences of string concatenation and
StringBuilder
, but does most of it.