C# › Arrays, Span<T> & Memory<T>

How would you write a high-performance CSV field parser using ReadOnlySpan<char> that avoids all intermediate string allocations?

Advanced

Answer

Use ReadOnlySpan<char>.IndexOf() or Split-style enumeration to locate delimiters directly within the original string's span, slicing out each field as its own ReadOnlySpan<char> — only convert a field to an actual 'string' (via .ToString()) at the very last moment when you genuinely need to store or return it as a heap-allocated string.
ReadOnlySpan<char> line = "Sam,30,Engineer".AsSpan();
int firstComma = line.IndexOf(',');
ReadOnlySpan<char> name = line.Slice(0, firstComma); // no allocation yet
ReadOnlySpan<char> rest = line.Slice(firstComma + 1);
// ... continue slicing 'rest' for remaining fields
Real-world example Parsing millions of lines of a large CSV or log file in a batch job where allocation overhead directly impacts throughput.

Common follow-ups: At what point in this pipeline would you actually be FORCED to allocate a real string?