Memory- and span-related types
Starting with .NET Core 2.1, .NET includes a number of interrelated types that represent a contiguous, strongly typed region of arbitrary memory. These include:
System.Span<T>, a type that is used to access a contiguous region of memory. A Span<T> instance can be backed by an array of type
T, a String, a buffer allocated with stackalloc, or a pointer to unmanaged memory. Because it has to be allocated on the stack, it has a number of restrictions. For example, a field in a class cannot be of type Span<T>, nor can span be used in asynchronous operations.
System.Memory<T>, a contiguous region of memory that is allocated on the managed heap rather than the stack. A Memory<T> instance can be backed by an array of type
Tor a String. Because it can be stored on the managed heap, Memory<T> has none of the limitations of Span<T>.
System.Buffers.MemoryPool<T>, which allocates strongly typed blocks of memory from a memory pool to an owner. IMemoryOwner<T> instances can be rented from the pool by calling MemoryPool<T>.Rent and released back to the pool by calling MemoryPool<T>.Dispose().
System.Buffers.IMemoryOwner<T>, which represents the owner of a block of memory and controls its lifetime management.
MemoryManager<T>, an abstract base class that can be used to replace the implementation of Memory<T> so that Memory<T> can be backed by additional types, such as safe handles. MemoryManager<T> is intended for advanced scenarios.
ArraySegment<T>, a wrapper for a particular number of array elements starting at a particular index.
For more information, see the System.Buffers namespace.
Working with memory and span
Because the memory- and span-related types are typically used to store data in a processing pipeline, it is important that developers follow a set of best practices when using Span<T>, Memory<T>, and related types. These best practices are documented in Memory<T> and Span<T> usage guidelines.