C# › Arrays, Span<T> & Memory<T>

How do you slice an array or string efficiently without allocating a new array/string, using Span<T> or ReadOnlySpan<T>?

Intermediate

Answer

Call .AsSpan() (with optional start/length arguments) on an array or string to get a Span<T> or ReadOnlySpan<char> view over just that portion — no new memory is allocated, unlike Substring() or array slicing with LINQ's Skip/Take, which both copy data.
string text = "Hello, World!";
ReadOnlySpan<char> hello = text.AsSpan(0, 5); // 'Hello', no allocation

int[] arr = { 1, 2, 3, 4, 5 };
Span<int> middle = arr.AsSpan(1, 3); // [2, 3, 4], no allocation
Real-world example Parsing a large log file line-by-line, slicing out fields without allocating a new string for every single token.

Common follow-ups: How much of a real-world performance difference does this make compared to Substring() in a hot parsing loop?