Home / Forums / Zero-Allocation String Splitting with MemoryExtensions.Split in .NET 8 / 9

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Source

Zero-Allocation String Splitting with MemoryExtensions.Split in .NET 8 / 9

SpanSpecialist
Zero-Copy Memory
MEMBER
Rep: 273
Join Date: Aug 2021
Posts: 7
Thanks: 33
1y ago · Oct 18, 2024 12:20 PM
#1
Standard
CODE
string.Split()
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,
CODE
MemoryExtensions.Split
slices directly into
CODE
ReadOnlySpan<char>
with zero heap allocations:


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 ...
The following users thanked SpanSpecialist for this post:
BytePusher
Memory & Performance
MEMBER
Rep: 209
Join Date: Dec 2025
Posts: 13
Thanks: 32
1y ago · Oct 18, 2024 3:31 PM
#2
CODE
input.Split()
returning a span enumerator is brilliant. In previous .NET versions, we had to write custom
CODE
SpanSplitEnumerator
structs to achieve this.
BytePusher · Memory & Performance
Zero-allocation C# code using Span<T>, Memory<T>, and Unsafe...
LinQ_Lover
C# Developer
MEMBER
Rep: 313
Join Date: Jul 2020
Posts: 8
Thanks: 27
1y ago · Oct 19, 2024 8:31 PM
#3
Combined with
CODE
int.Parse(span)
or
CODE
bool.Parse(span)
, you can parse structured telemetry strings from sockets with 0 total bytes allocated on the GC heap!
LinQ_Lover · C# Developer
Clean code, fluent LINQ expressions, and expressive C# patte...