perf: reduce allocations with Span.Split and VSB#4279
perf: reduce allocations with Span.Split and VSB#4279thomhurst merged 1 commit intothomhurst:mainfrom
Span.Split and VSB#4279Conversation
SummaryOptimizes stack trace filtering to reduce allocations using Critical IssuesNone found ✅ SuggestionsMinor optimization opportunity: var vsb = new ValueStringBuilder(stackalloc char[256]);
var enumerator = stackTrace.AsSpan().Split(Environment.NewLine);
var isFirst = true;
foreach (var range in enumerator)
{
var slice = stackTrace.AsSpan()[range];
if (slice.Trim().StartsWith("at TUnit"))
{
break;
}
if (!isFirst)
{
vsb.Append(Environment.NewLine);
}
vsb.Append(slice);
isFirst = false;
}However, the current implementation is clear and correct, so this is entirely optional. Alignment with TUnit Rules✅ Performance First (Rule 4): This change directly aligns with TUnit's performance-first principle. Exception handling is in the execution hot path (every test failure creates a ✅ AOT Compatible (Rule 5): Uses span-based APIs compatible with Native AOT. ✅ Modern C# (Code Principle): Leverages latest .NET features (Span APIs, stackalloc, ValueStringBuilder). The Polyfill package ensures Verdict✅ APPROVE - Great performance improvement with correct implementation! |
|
How does the stackalloc work if there's more than 256 chars? |
We initialise Just like any other value on the stack, the This is true for |
5b35434 to
3aeae42
Compare
Use
ValueStringBuilderandSpan.Splitto avoid allocatingstring[]andstring.SubstringNote that while the savings are small for modern versions of .NET - 2.5MB, this represents a substantial speedup for .NET framework where
string.Splitwould allocate 60MB ofint[]Before
After