Skip to content
Tutorials Center
My learning

Topics

Lesson 108 of 182 ยท Memory and Performance

Span, Memory and Slicing

Learn Span<T>, ReadOnlySpan<T>, stackalloc and Memory<T> in C#: slice arrays and strings without allocating, parse text fast and understand the ref struct rules.

Imagine you have a line of text such as "2025-03-14" and you want the year, month and day as numbers. The obvious code calls Substring three times. Each call allocates a brand-new string on the heap just so you can read three small numbers and throw the strings away. In a loop over a million lines, that is three million temporary objects for the garbage collector to clean up.

Span<T> and ReadOnlySpan<T> solve this. A span is a lightweight window onto a stretch of memory that already exists (an array, a string, a block on the stack). Slicing a span creates a new window over the same memory without copying anything. This lesson shows how spans work, how to measure their effect, what stackalloc and Memory<T> add, and the rules that keep spans safe.

What a span is

A Span<T> is a small struct holding two things: a reference to the first element and a length. That is all. It does not own the memory and it cannot grow. Because it is a struct, creating one costs no heap allocation.

C# Windows onto an array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Writing to the span changes the array, because they are the same memory. That is the whole idea: no copy, one memory region, many views. Slicing with ranges ([4..]) uses the same syntax you know from ranges and indices.

ReadOnlySpan for text and constants

ReadOnlySpan<T> is the same window, but you cannot write through it. Strings are immutable, so a string converts implicitly to ReadOnlySpan<char>, and AsSpan() gives you windows onto parts of it.

C# Parsing a date without Substring

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Many core methods have span overloads for exactly this reason: int.Parse, Guid.TryParse, string.Concat, Path.GetFileName, Encoding.UTF8.GetBytes, MemoryExtensions.Split, and more. When you see an overload taking ReadOnlySpan<char>, it is the allocation-free path.

Proving there is no allocation

Do not take performance claims on trust; measure them. GC.GetAllocatedBytesForCurrentThread() returns the bytes the current thread has allocated, which is exact and does not depend on timing (unlike clocks, which are covered in measuring performance).

C# Counting the bytes: Substring versus spans

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The span version allocates nothing. The substring version allocates three strings per call, about 32 bytes each on a 64-bit runtime, so roughly 100 KB over the loop. Exact byte counts depend on the runtime, which is why we print a boolean for that one.

stackalloc: small buffers on the stack

Sometimes you need a short-lived scratch buffer, say 64 bytes to format something. new byte[64] allocates on the heap. With stackalloc, the memory comes from the method's stack frame and disappears when the method returns, with no GC involvement. Assigning it to a Span<T> makes it safe without unsafe code.

C# A scratch buffer on the stack

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The only heap allocation is the final string we return. Rules of thumb for stackalloc:

  • Keep it small. The stack is about 1 MB on most platforms (8 MB on Linux main threads), and overflowing it crashes the process, which you cannot catch. A few hundred bytes up to roughly a kilobyte is typical.
  • Never stackalloc inside a loop without a bound; the memory is only released when the method ends.
  • For a size that might be large, fall back to the heap or an array pool:
C#
Span<byte> buffer = size <= 256
    ? stackalloc byte[size]
    : new byte[size];

Spans and methods

Spans work well as parameters, because the caller can pass an array, part of an array, a string, a stackalloc block or a List<T>'s contents (via CollectionsMarshal.AsSpan) without conversion. A method that only reads should take ReadOnlySpan<T>.

C# One method for many sources

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice the collection expression [7, 7, 7] converted straight to a ReadOnlySpan<int>; the compiler can even place the data in read-only memory without allocating (collection expressions). C# 14 also added more implicit conversions between arrays, Span<T> and ReadOnlySpan<T>, so extension methods on spans are easier to call on arrays.

Useful span methods to know: IndexOf, Contains, StartsWith, SequenceEqual, Trim, Reverse, Sort, CopyTo, Fill, Clear and Slice.

The ref struct rules

A span can point into the stack, so the compiler must make sure it never outlives that memory. That is why Span<T> is a ref struct, a type that can only live on the stack. The rules follow from that:

  • It cannot be a field of a normal class or struct.
  • It cannot be boxed, so it cannot be cast to object, and it cannot be a generic type argument unless the generic type opts in with allows ref struct (C# 13).
  • It cannot be captured by a lambda or local function that may outlive the call.
  • In ordinary async methods and iterators, you cannot keep a span across an await or yield. (C# 13 relaxed this for parts of the method that do not cross those points.)

The compiler enforces these with real errors. Here is what a field attempt looks like:

C# A span as a class field (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler reports error CS8345: Field or auto-implemented property cannot be of type 'Span<int>' unless it is an instance member of a ref struct. The fix is to make Holder a ref struct as well, or to store a Memory<int> instead.

Memory of T: when a span will not do

When data must be stored in a field, captured, or passed across an await, use Memory<T> (or ReadOnlyMemory<T>). It is an ordinary struct that remembers an array (or other memory owner) plus an offset and length. You turn it into a span with .Span at the moment you need to read or write.

C# Memory in a field

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Memory<T> is exactly what async APIs use: Stream.ReadAsync(Memory<byte>, ...) and WriteAsync(ReadOnlyMemory<byte>, ...) replaced the older byte[]-plus-offsets overloads, see streams and I/O.

Type Where it can live Typical use
Span<T> / ReadOnlySpan<T> Stack only (ref struct) Synchronous parsing, slicing, scratch buffers
Memory<T> / ReadOnlyMemory<T> Anywhere (fields, heap, across await) Buffers stored in objects or used by async code
T[] Heap Owning storage

Pitfalls and good practice

  • Spans are not owners. A span over a List<T>'s internal array (CollectionsMarshal.AsSpan) becomes stale if the list grows and reallocates. Do not hold it across list modifications.
  • Do not return a span over a local stack buffer. The compiler rejects it because the memory would vanish.
  • Spans make code harder to read. Use them in hot paths and parsing code that you have measured, not everywhere. For everyday code, string.Split and Substring are fine.
  • Prefer built-in span APIs such as MemoryExtensions.Split (a ref struct enumerator over ranges, .NET 9 and later) to hand-written index arithmetic.
C# Splitting text without creating substrings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Whenever you write s.Substring(...) or array[a..b] on an array (which copies!) only to read the result once, ask whether AsSpan or a ReadOnlySpan<char> overload would do the job. Slicing a span never copies; slicing an array with a range does.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does slicing a Span<T> do?

    A span is a pointer plus a length. Slicing just produces another pointer and length over the same memory, so writes through the slice change the original data.
  2. 2. Why can a Span<T> not be a field of an ordinary class?

    Span<T> is a ref struct that must stay on the stack. The compiler reports error CS8345 if you try to put it into a field of a normal type. Use Memory<T> to store a window.
  3. 3. Which type should you choose for a buffer that must be used across an await?

    Memory<T> is an ordinary struct that can live in fields and survive await points. You call .Span when you need to touch the data synchronously.
  4. 4. What is a good guideline for stackalloc?

    The stack is small and overflowing it crashes the process. Assigning stackalloc to a Span<T> needs no unsafe code, and a size check with a heap fallback keeps it safe.
  5. 5. int.Parse(text.Substring(0, 4)) versus int.Parse(text.AsSpan(0, 4)): what is the difference?

    Both parse the same characters. Substring creates a new string object, whereas the span overload reads straight from the original string's memory.

Summary

  • Span<T> and ReadOnlySpan<T> are allocation-free windows (pointer plus length) over arrays, strings, stack memory and more. Slicing never copies.
  • Use ReadOnlySpan<char> overloads of Parse, Split, Trim and friends to process text without temporary strings.
  • stackalloc into a Span<T> gives short-lived scratch buffers with no GC cost; keep them small and bounded.
  • Spans are ref structs: no fields of normal types, no boxing, no capture by lambdas, and limits around await and yield.
  • Memory<T> is the storable, async-friendly cousin; call .Span to work with its data.
  • Measure with GC.GetAllocatedBytesForCurrentThread() and use spans where it matters, not everywhere.

Next: Boxing, Unboxing and Value Semantics