Cut allocations in C# with Span<T> and Memory<T>
8 steps · about 1 h 58 min · Intermediate
- Learn what spans and memory types are for (doc, Microsoft Learn, 10 min)
Introduces the family of types for working with contiguous memory safely.
- Slice strings and arrays without copying (article, MSDN Magazine, 30 min)
The classic deep dive shows how Span<T> works and why it is fast.
- Use the Span<T> API in parsing code (doc, Microsoft Learn, 15 min)
Lists the slicing, copying and search members you will call most.
- Respect the rules of ref struct types (reference, Microsoft Learn, 10 min)
Explains why a span cannot be boxed, captured or stored on the heap.
- Allocate small buffers on the stack with stackalloc (reference, Microsoft Learn, 8 min)
Shows the safe span-based form and when stack buffers are appropriate.
- Follow the ownership rules for Memory<T> (guide, Microsoft Learn, 20 min)
Gives the rules for passing buffers across async and API boundaries.
- Rent and return buffers with ArrayPool<T> (doc, Microsoft Learn, 10 min)
Pooling removes repeated large-array allocations in busy code paths.
- Measure allocations with the BenchmarkDotNet memory diagnoser (link, BenchmarkDotNet, 15 min)
Proves the change cut allocated bytes per operation.