.NET includes a number of interrelated types that represent a contiguous, strongly typed region of arbitrary memory. These types are designed to allow the creation of algorithms that avoid copying memory or allocating on the managed heap more than necessary. Creating them (either via Slice, AsSpan(), a collection expression, or their constructors) does not involve duplicating the underlying buffers: only the relevant references and offsets, which represent the "view" of the wrapped memory, are updated. In high-performance code, spans are often used to avoid allocating strings unnecessarily.
The types include:
System.Span, a type that's used to access a contiguous region of memory. A System.Span instance can be backed by an array of type
T, 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 System.Span, nor can span be used in asynchronous operations.System.ReadOnlySpan, an immutable version of the System.Span structure. Instances can be also backed by a System.String.
System.Memory, a wrapper over a contiguous region of memory. A System.Memory instance can be backed by an array of type
Tor a memory manager. As it can be stored on the managed heap, System.Memory has none of the limitations of System.Span.System.ReadOnlyMemory, an immutable version of the System.Memory structure. Instances can also be backed by a System.String.
System.Buffers.MemoryPool, which allocates strongly typed blocks of memory from a memory pool to an owner. System.Buffers.IMemoryOwner instances can be rented from the pool by calling System.Buffers.MemoryPool.Rent and released back to the pool by calling System.Buffers.MemoryPool.Dispose.
System.Buffers.IMemoryOwner, which represents the owner of a block of memory and controls its lifetime management.
System.Buffers.MemoryManager, an abstract base class that can be used to replace the implementation of System.Memory so that System.Memory can be backed by additional types, such as safe handles. System.Buffers.MemoryManager is intended for advanced scenarios.
System.ArraySegment, a wrapper for a particular number of array elements starting at a particular index.
System.MemoryExtensions, a collection of extension methods for converting strings, arrays, and array segments to System.Memory blocks.
For more information, see the System.Buffers namespace.
Working with memory and span
Because the memory-related and span-related types are typically used to store data in a processing pipeline, it's important that you follow a set of best practices when using System.Span, System.Memory, and related types. These best practices are documented in Memory<T> and Span<T> usage guidelines.