What is Span<T> and Memory<T>?

.NET Framework & CLR Memory Advanced 3–5 Yrs5+ Yrs Conceptual 1 min read

Quick Answer

Span<T> is a lightweight view over a contiguous region of memory — an array, a slice of one, a stackalloc buffer, or native memory — with no allocation. You can slice and parse without creating substrings/subarrays. It's a ref struct, so it can't be stored on the heap or used in async; Memory<T> is the heap-safe equivalent for those cases.

Span<T> is a zero-allocation window into some contiguous memory — it could be pointing at an array, a slice of an array, a stack buffer, or unmanaged memory. The big win is parsing: instead of calling Substring and allocating a new string for every token, I slice a ReadOnlySpan<char> and parse directly. It's a ref struct so it lives on the stack and can't be captured in an async method or stored as a field — Memory<T> is the version for those situations. It's a performance tool for parsers and serializers, not something I'd reach for in normal business code.

  • ReadOnlySpan<char> slicing replaces Substring allocations in parsing hot paths.
  • stackalloc int[64] as a Span<int> for a small scratch buffer with zero GC.
  • Methods like int.Parse(ReadOnlySpan<char>), string.AsSpan(), Span.Slice().
  • Memory<T> can be a field, awaited around, and converted to a span when you need to touch the data.
  • Mostly relevant for high-throughput libraries, serialization, and parsing — not everyday CRUD code.