Span<T>
and Memory<T>
are high-performance types introduced in C# 7.2 for working with contiguous memory regions (e.g., arrays, strings, or stack-allocated memory). They help reduce allocations and improve performance in scenarios like parsing, slicing, and processing large datasets.
Span<T>
?A ref struct that provides a type-safe and memory-safe view over a contiguous region of memory.
Can point to arrays, stack memory, or unmanaged memory.
Cannot be used on the heap (e.g., as a field in a class or in async methods).
int[] array = { 1, 2, 3, 4, 5 };
Span<int> slice = array.AsSpan(1, 3); // Points to { 2, 3, 4 }
foreach (var item in slice)
{
Console.WriteLine(item); // Output: 2, 3, 4
}
Memory<T>
?Similar to Span<T>
, but it’s not a ref struct, so it can be used on the heap (e.g., in async methods or as a field in a class).
Useful when you need to work with memory in asynchronous contexts.
Memory<T>
in Async Codeasync Task ProcessDataAsync(Memory<int> data)
{
await Task.Delay(100); // Simulate async work
foreach (var item in data.Span)
{
Console.WriteLine(item);
}
}
// Usage
int[] array = { 1, 2, 3, 4, 5 };
await ProcessDataAsync(array.AsMemory(1, 3)); // Output: 2, 3, 4
Performance:
Avoids unnecessary allocations (e.g., slicing arrays without creating new arrays).
Memory Safety:
Provides bounds checking to prevent buffer overflows.
Flexibility:
Works with arrays, strings, stack memory, and unmanaged memory.
Parsing Strings:
Efficiently parse strings without creating substrings.
string input = "123,456,789";
ReadOnlySpan<char> span = input.AsSpan();
int index = span.IndexOf(',');
ReadOnlySpan<char> firstNumber = span.Slice(0, index); // Points to "123"
Processing Large Data:
Process large datasets (e.g., files or network streams) without allocating additional memory.
Stack Allocation:
Use stackalloc
with Span<T>
for high-performance, low-overhead memory usage.
Span<T>
cannot be used in async methods or as a field in a class (use Memory<T>
instead).
Span<T>
and Memory<T>
are only available in .NET Core 2.1+ and .NET 5+.