Advertisement
Advanced C#, Arrays, Span<T> & Memory<T>

How does the modern .NET Span-based string.Split (via MemoryExtensions) or manual span-splitting reduce garbage collection pressure compared to string.Split()?

Short answer

Regular string.Split() allocates a new string array AND a new string object for EVERY resulting substring; span-based splitting techniques (like a manual span-walking loop, or newer .NET SpanSplitEnumerator APIs) can iterate over each segment as a ReadOnlySpan without allocating…

Save C# mock interview
Advertisement
AModel answer
Regular string.Split() allocates a new string array AND a new string object for EVERY resulting substring; span-based splitting techniques (like a manual span-walking loop, or newer .NET SpanSplitEnumerator APIs) can iterate over each segment as a ReadOnlySpan<char> without allocating anything for segments you only need to read or compare, not store.
ReadOnlySpan<char> csv = "a,b,c,d,e".AsSpan();
foreach (var segment in csv.Split(',')) { // conceptual, using newer span-splitting APIs
  // process each segment as a span, zero string allocations
}
// vs. "a,b,c,d,e".Split(',') -- allocates a string[] AND 5 string objects
Real-world example
Reducing GC pauses in a high-throughput data ingestion pipeline processing millions of delimited records per second.
Likely follow-ups
  • Why does reducing allocations matter more for GC PAUSE TIME than for raw memory usage in a server application?
Related topics