What is Span<T> and what core performance problem does it solve?
Short answer
Span is a stack-only (ref struct) type representing a contiguous, type-safe view over a region of memory — it lets you slice arrays, strings, or stack-allocated memory WITHOUT copying data, avoiding the allocation overhead of creating new sub-arrays or substrings for temporary…
Advertisement
AModel answer
Span<T> is a stack-only (ref struct) type representing a contiguous, type-safe view over a region of memory — it lets you slice arrays, strings, or stack-allocated memory WITHOUT copying data, avoiding the allocation overhead of creating new sub-arrays or substrings for temporary operations.
int[] source = { 1, 2, 3, 4, 5 };
Span<int> slice = source.AsSpan(1, 3); // view over elements [2, 3, 4], no copy
slice[0] = 99; // mutates the original array too, since it's a viewReal-world example
Parsing a large string or byte buffer in-place (e.g., a CSV line) without allocating a new substring for every field.
Likely follow-ups
- Why can't Span<T> be stored as a field in a regular (non-ref struct) class?
Related topics