High Performance C#: Span and Memory

String manipulation in C# has historically been allocation-heavy. `Substring()` creates a new string on the heap. In high-throughput scenarios (web servers, parsers), this leads to Garbage Collection (GC) pauses.

The Solution: Span<T>

Span<T> is a struct that represents a contiguous region of memory. It can point to part of a string or array without allocating new memory.

string data = "Content-Length: 123";
ReadOnlySpan<char> span = data.AsSpan();

// Zero allocation slice!
ReadOnlySpan<char> lengthPart = span.Slice(16); 
int length = int.Parse(lengthPart);

The `Slice` operation is practically free. We used this to optimize a CSV parser processing 1GB files, reducing memory usage from 4GB to 50MB.


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.