1.25 — Span<T>, Memory<T>, stackalloc¶
← Roadmap · Section: 1. C# Language Fundamentals Prev: 1.24 Partial classes and local functions · Next: 1.26 Modern C# by version
Markers: 🧠 · Confidence: 🔴 · Last reviewed: —
TL;DR¶
- A
Span<T>is a window onto memory you already have. Slicing one costs nothing — no copy, no allocation. Span<T>can only live on the stack. That means you cannot use it in anasyncmethod, store it in a field, or put it in a list.Memory<T>is the version that can live on the heap. Use it when you need async.
The concept¶
Imagine you have a 10,000-character string and you want characters 500 to 600.
Substring(500, 100) gives you a new string — which means allocating memory and copying
100 characters into it. If you do that in a loop, you create a lot of garbage.
Span<T> gives you a different option: a window.
Think of a long strip of paper with writing on it, and a piece of card with a rectangular hole cut in it. Put the card over the paper and you can see just the part you want. You did not copy anything. You did not cut the paper. You just narrowed what you are looking at, and you can slide the card along for free.
That is a span. It holds a pointer to where the data starts and how long the window is. Nothing else.
string text = "Hello, World!";
var copy = text.Substring(7, 5); // "World" — allocates a new string
var slice = text.AsSpan(7, 5); // "World" — allocates NOTHING
Both give you "World". Only one of them costs memory.
How it works¶
Slicing is free¶
Span<int> numbers = new int[1000];
var firstHalf = numbers[..500]; // no allocation
var secondHalf = numbers[500..]; // no allocation
var middle = numbers.Slice(250, 500); // no allocation
Each of these is just a new pointer-and-length pair. It is a handful of bytes on the stack, and creating one is essentially free.
A span is a view, not a copy — so writing through it changes the original:
Span<int> data = new int[] { 1, 2, 3, 4, 5 };
Span<int> part = data[1..3];
part[0] = 99;
Console.WriteLine(data[1]); // 99 — we changed the original array
ReadOnlySpan<T>¶
The read-only version. string.AsSpan() gives you a ReadOnlySpan<char>, because strings
cannot be changed (1.3).
ReadOnlySpan<char> span = "Hello, World!".AsSpan();
ReadOnlySpan<char> word = span[7..12]; // "World", no allocation
The restrictions — and why they exist¶
Span<T> is a ref struct. That is a special kind of struct that the compiler
guarantees will only ever live on the stack, never on the heap.
That guarantee is what makes it safe. A span points directly at memory. If a span could outlive the thing it points at, you would have a pointer to memory that has been freed or moved — exactly the class of bug that managed languages exist to prevent.
So the compiler enforces these rules:
class MyClass
{
private Span<int> _span; // ERROR — fields live on the heap
}
async Task DoWork()
{
Span<int> span = stackalloc int[10];
await Task.Delay(1); // ERROR — span cannot cross an await
}
var list = new List<Span<int>>(); // ERROR — list contents live on the heap
Span<int> Get() => stackalloc int[10]; // ERROR — the stack memory is gone on return
The async one is the restriction you will hit most often. When a method awaits, all its
local variables get moved into a heap object so they survive the pause. A span cannot go on
the heap, so it cannot survive an await.
Memory<T> — the heap-friendly version¶
Memory<T> is a normal struct, so it can live on the heap. That means it works in async
methods, can be stored in fields, and can be put in collections.
async Task ProcessAsync(Memory<byte> buffer, CancellationToken ct)
{
await stream.ReadAsync(buffer, ct); // fine — Memory survives the await
Span<byte> span = buffer.Span; // convert when you need to work with it
ProcessSynchronously(span);
}
The pattern: use Memory<T> for the parts that cross an await, and call .Span to
get a Span<T> for the tight synchronous work in between.
Memory<T> is slightly slower than Span<T> because it stores an object reference plus an
offset rather than a direct pointer, so every access has a small extra step.
stackalloc¶
Allocates an array directly on the stack instead of the heap:
No heap allocation and no garbage collection — the memory is reclaimed automatically when the method returns.
But the stack is small — usually about 1 MB per thread. Allocate too much and you get a
StackOverflowException, which cannot be caught and kills the process immediately.
So the rules are strict:
- Keep it small. A few hundred bytes to a couple of kilobytes.
- Never inside a loop — each iteration adds more and none is released until the method returns.
- Never with a size that comes from user input.
The safe pattern is to check the size and fall back to a pooled array:
const int MaxStack = 256;
Span<byte> buffer = length <= MaxStack
? stackalloc byte[MaxStack]
: new byte[length];
Code¶
A realistic parser, showing the difference clearly.
// BEFORE — allocates a string for every field on every line
public static Order ParseLine(string line)
{
var parts = line.Split(','); // allocates: array + one string per part
return new Order
{
Id = Guid.Parse(parts[0]),
Customer = parts[1],
Total = decimal.Parse(parts[2])
};
}
For a million-line file, that is millions of temporary strings, all of which the garbage collector has to clean up.
// AFTER — no allocation for parsing, only for what we actually keep
public static Order ParseLine(ReadOnlySpan<char> line)
{
var i1 = line.IndexOf(',');
var idSpan = line[..i1];
var rest = line[(i1 + 1)..];
var i2 = rest.IndexOf(',');
var customerSpan = rest[..i2];
var totalSpan = rest[(i2 + 1)..];
return new Order
{
Id = Guid.Parse(idSpan), // parses directly from the span
Customer = customerSpan.ToString(), // only allocate what we keep
Total = decimal.Parse(totalSpan)
};
}
The key detail: Guid.Parse and decimal.Parse have overloads that take a
ReadOnlySpan<char> directly. Most .NET parsing APIs do now. So you never create the
intermediate strings at all — you only allocate the one string you actually store.
Should you use this everywhere?¶
No. This code is harder to read than Split, and in most application code that
readability cost is not worth it.
Span<T> belongs in:
- Parsers and serializers processing large volumes
- Hot loops that show up in a profiler
- Library code where you do not know how often you will be called
For a controller action that runs a few hundred times a second, Split is completely fine.
Measure before you reach for this. Being able to say that in an interview is as
valuable as knowing the feature exists.
Interview questions¶
Q: What is Span<T> and what problem does it solve?
It is a view over a contiguous block of memory — an array, a string, or stack-allocated
memory. It holds a pointer and a length and nothing else, so creating one or slicing one
costs nothing. The problem it solves is the allocations you get from operations like
Substring and Split, which copy data into new objects. With a span you can work on part
of existing data without copying it, which removes a lot of garbage collection pressure in
parsing and serialization code.
Q: Why can't you use Span<T> in an async method?
Because it is a ref struct, which the compiler guarantees will only ever live on the
stack. When a method awaits, its local variables have to be moved into a heap object so
they survive the suspension — and a span cannot go on the heap. That restriction is what
makes spans safe: it guarantees the span can never outlive the memory it points at. When
you need something span-like across an await, you use Memory<T>, which is a normal struct
and can live on the heap, then convert to a span with .Span for the synchronous work.
Q: What is stackalloc and what should you be careful about?
It allocates an array on the stack rather than the heap, so there is no allocation and no
garbage collection — the memory disappears when the method returns. The danger is that the
stack is small, typically around a megabyte per thread, and overflowing it throws a
StackOverflowException that cannot be caught and kills the process. So you keep it to a
few hundred bytes, never put it in a loop, and never size it from user input. The usual
pattern is to stack-allocate below a fixed threshold and fall back to a heap or pooled
array above it.
Q: When should you actually use spans?
When a profiler tells you allocations are a problem — typically parsers, serializers, and
hot loops handling large volumes of data. Span-based code is noticeably harder to read than
the equivalent using Substring and Split, so in normal application code that trade is
not worth making. It is much more at home in library code, where you do not control how
often you are called.
Traps ⚠️¶
Span<T>cannot be a field, cannot be used in async methods, and cannot go in a collection. All because it is stack-only.stackallocin a loop will overflow the stack. Each iteration adds more; nothing is released until the method returns.- A
StackOverflowExceptioncannot be caught. The process dies immediately. - A span is a view, not a copy. Writing through it changes the original data, which is
surprising if you expected
Substringbehaviour. Memory<T>is slower thanSpan<T>. It stores an object reference plus an offset, so each access has an extra indirection.- Do not reach for this without measuring. The readability cost is real and the benefit only shows up at volume.
- A span over an array can be invalidated if the array is resized elsewhere. Do not hold one longer than the immediate operation.
Related¶
- 1.1 Stack vs heap — the memory model underneath
- 1.2 readonly struct —
Span<T>is aref struct - 1.3 Strings —
AsSpan()as the no-allocationSubstring - 3.4 Garbage collection — the pressure spans relieve
- 19.13 Reducing allocations — spans alongside
ArrayPool - 19.14 Benchmarking — measuring before optimising