Span
Intro
Span<T> is a stack-only view over contiguous memory. It does not own data, it only points to existing memory (array, stackalloc buffer, or unmanaged memory). Use it when you need high-performance slicing/parsing with minimal allocations.
Span<T> gives bounds-checked access to a contiguous region with very low overhead:
- Slicing creates lightweight subviews without copying data.
- It can wrap array segments and stack-allocated buffers.
- Because it is a
ref struct, it cannot escape to the managed heap.
Structure
graph LR
A[array zero ten] --> B[array one twenty] --> C[array two thirty] --> D[array three forty]
S[span start two length two] --> C
S --> DExample
Span<int> values = stackalloc int[] { 10, 20, 30, 40 };
Span<int> tail = values.Slice(2); // 30, 40
tail[0] = 300;
Console.WriteLine(values[2]); // 300
Pitfalls
- Returning a
Span<T>that points to stack memory is invalid because the underlying buffer is gone after method return. Keep span lifetimes within the owning scope. Span<T>cannot be used acrossawaitboundaries because it is stack-only. UseMemory<T>for async flows.- Converting every API to
Span<T>can hurt readability when performance is not a bottleneck. Apply it to measured hot paths.
Tradeoffs
Span<T>vsT[]: spans avoid copies for slicing, arrays are simpler when you need ownership and long-lived storage.Span<T>vsMemory<T>: spans are best for synchronous fast paths,Memory<T>is better when data must survive async boundaries.
Questions
Why is
Span<T> a ref struct?It prevents the span from being boxed or moved to the heap, which protects memory safety for references to stack and unmanaged buffers.
When should you choose
Memory<T> instead of Span<T>?
Use Memory<T> when the buffer must cross async boundaries, be stored in fields, or live longer than a single synchronous scope.
Links
Span<T>struct — API reference covering constructors, Slice, and ref struct constraints.Memory<T>andSpan<T>usage guidelines — Microsoft guidance on when to use Span vs Memory, ownership rules, and async boundaries.- Welcome to C# 7.2 and Span — .NET blog post introducing
Span<T>with motivation, design rationale, and early usage examples.
Whats next
Parent
02 Computer Science
Pages