.NETHard
What is the difference between Span<T> and Memory<T>?
Both are zero-allocation views into a contiguous block of memory, but they differ in where they can live.
Span is a ref struct — stack-only:
public static int SumDigits(ReadOnlySpan<char> s) {
int sum = 0;
foreach (var c in s) if (char.IsDigit(c)) sum += c - '0';
return sum;
}
SumDigits("order-2026-04".AsSpan(6, 4)); // no alloc
Can't be:
- Stored in a class field
- Captured in a closure
- Held across
awaitoryield return
Memory is a normal struct — heap-friendly. Use when you need to pass a buffer across async boundaries:
public async Task ProcessAsync(ReadOnlyMemory<byte> buffer) {
await Task.Delay(10); // ✓ Memory survives await
var span = buffer.Span; // pin/unpin only when needed
DoSync(span);
}
Rule: prefer Span<T> for tight synchronous loops, Memory<T> when crossing async or storing a buffer. The conversion is cheap (memory.Span).