High Performance C#: Span and Memory

`Span<T>` allows you to work with contiguous memory regions (Arrays, Stack, Native Heap) without allocating new objects. It’s the secret sauce behind Kestrel’s speed.

Slicing without Allocation

string data = "123,456,789";
ReadOnlySpan<char> span = data.AsSpan();

// No "Substring" allocation! Just a window over existing memory.
var part1 = span.Slice(0, 3); 
int value = int.Parse(part1); // 123

Stackalloc

Allocate memory on the stack (super fast, auto-cleaned) instead of the heap (GC pressure).

Span<byte> buffer = stackalloc byte[1024]; // 1KB on stack
Random.Shared.NextBytes(buffer);
ProcessData(buffer);

Key Takeaways

  • `Span<T>` is a `ref struct`, meaning it can only live on the stack (cannot be a field in a class).
  • Use `Memory<T>` if you need to store it on the heap (e.g., in async methods).
  • Most .NET APIs (IO, Parsing) now accept Span for free performance wins.

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.