Advertisement
Advanced .NET, CLR & Runtime

How does Span<T> improve performance for buffer and array manipulation compared to traditional array slicing?

Short answer

Span 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…

Save .NET mock interview
Advertisement
AModel answer
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 array
Real-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.
Likely follow-ups
  • Why can't Span<T> be stored as a field in a class or used across await boundaries?
  • What's the difference between Span<T> and Memory<T> in terms of these restrictions?
Related topics