Cut allocations in C# with Span<T> and Memory<T>

8 steps · about 1 h 58 min · Intermediate

  1. Learn what spans and memory types are for (doc, Microsoft Learn, 10 min)

    Introduces the family of types for working with contiguous memory safely.

  2. 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.

  3. Use the Span<T> API in parsing code (doc, Microsoft Learn, 15 min)

    Lists the slicing, copying and search members you will call most.

  4. 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.

  5. 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.

  6. Follow the ownership rules for Memory<T> (guide, Microsoft Learn, 20 min)

    Gives the rules for passing buffers across async and API boundaries.

  7. Rent and return buffers with ArrayPool<T> (doc, Microsoft Learn, 10 min)

    Pooling removes repeated large-array allocations in busy code paths.

  8. Measure allocations with the BenchmarkDotNet memory diagnoser (link, BenchmarkDotNet, 15 min)

    Proves the change cut allocated bytes per operation.