perf: add capacity to StringBuilder in ValueAssertion
#4441
+2
−1
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.
By default
StringBuilderstarts with a capacity of 16. This is a problem inValueAssertionas it initialisesContextwith aStringBuilderbefore appending$"Assert.That({expression ?? "?"})", at a minimum this is 14 characters which is fine, but in the common case where the expression is not null, it will exceed the default of 16 and immediately have to add anotherStringBuilder.This pretty much guaranteed that any instance of
ValueAssertionwould allocate 2StringBuilderand 2char[]on initialisation.I solved this by initialising the
StringBuilderwith13 + expression.Length.The question is: how much additional capacity should be given? Too small and you frequently pay the cost to create a new
StringBuilderandchar[], too large and you over allocate achar[]. Making this decision based too much on the benchmarks would be optimising for the benchmarks and not real life. WDYTBefore
(expression?.Length ?? 1) + 13no unused space, the follwing assertion will have to create a newStringBuilder(expression?.Length ?? 1) + 24aka unused length of 11###
(expression?.Length ?? 1) + 32aka unused length of 19Note that the benchmarks give a general idea