1y ago · Oct 18, 2024 12:20 PM
Standard allocates an array of strings on the heap. If you are parsing CSV lines, log entries, or HTTP query parameters, it generates thousands of GC objects.
In .NET 8/9, slices directly into with zero heap allocations:
CODE
string.Split()In .NET 8/9,
CODE
MemoryExtensions.Split CODE
ReadOnlySpan<char> CSHARP
ReadOnlySpan<char> input = "USER_ID=1492&ROLE=Admin&ACTIVE=True";
// Zero heap allocation span enumerator!
foreach (Range range in input.Split('&'))
{
ReadOnlySpan<char> segment = input[range];
// Split key and value
int eqIdx = segment.IndexOf('=');
if (eqIdx != -1)
{
ReadOnlySpan<char> key = segment.Slice(0, eqIdx);
ReadOnlySpan<char> val = segment.Slice(eqIdx + 1);
Console.WriteLine($"Key: {key.ToString()}, Value: {val.ToString()}");
}
}
SpanSpecialist · Zero-Copy Memory
Span<T>, ReadOnlySpan<T>, and stackalloc for fast substring ...
Span<T>, ReadOnlySpan<T>, and stackalloc for fast substring ...
The following users thanked SpanSpecialist for this post: