Select a result to preview
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:
ref struct, it cannot escape to the managed heap.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 --> DSpan<int> values = stackalloc int[] { 10, 20, 30, 40 };
Span<int> tail = values.Slice(2); // 30, 40
tail[0] = 300;
Console.WriteLine(values[2]); // 300
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 across await boundaries because it is stack-only. Use Memory<T> for async flows.Span<T> can hurt readability when performance is not a bottleneck. Apply it to measured hot paths.Span<T> vs T[]: spans avoid copies for slicing, arrays are simpler when you need ownership and long-lived storage.Span<T> vs Memory<T>: spans are best for synchronous fast paths, Memory<T> is better when data must survive async boundaries.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.
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.
No. Slice creates another view over the same memory region. This is why spans are useful for allocation-sensitive parsing and protocol handling.
Parent
02 Computer Science
Pages