.NET › CLR & Runtime
How does Span<T> improve performance for buffer and array manipulation compared to traditional array slicing?
AdvancedAnswer
Span<T> is a stack-only (ref struct) type providing a type-safe, memory-safe view over a contiguous region of memory (an array, a slice of an array, stack-allocated memory, or unmanaged memory) without copying the underlying data -- unlike array slicing operations that allocate a new array, Span<T> operations like Slice() are zero-allocation, dramatically reducing garbage collection pressure in performance-critical code that frequently works with sub-ranges of buffers.
byte[] buffer = new byte[1000];
Span<byte> span = buffer;
Span<byte> slice = span.Slice(10, 50); // zero-allocation view, no copy
// Compare to traditional approach:
byte[] copy = buffer.Skip(10).Take(50).ToArray(); // allocates a new arrayReal-world example A network protocol parser processing incoming byte buffers uses Span<byte> throughout to slice and parse header fields without any intermediate array allocations, significantly reducing GC pressure under high message throughput.