C# System.Span<T>, System.Memory<T> System.Buffers.MemoryPool<T>

T.Zacks 3,936 Reputation points

I have visited this url https://learn.microsoft.com/en-us/dotnet/standard/memory-and-spans/ and found new classes are there called


the usage of above classes are not very clear after reading from MSDN LINK.

i really want to understand usage of above classes with a easy example.

i often usage List<T> but instead of List<T> can i use Span<T> for low memory consumption?

I guess Array store data in contiguous memory. how Span<T> is different from Array?

please some good usage of Span<T>


An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
8,185 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 41,626 Reputation points

    No you cannot use Span<T> in lieu of List<T>. List<T> stores a set of items and can grow and shrink over time. Span<T> is a view into an existing set of data that is optimized to not require memory allocations. If you don't understand what Span<T> is then you don't need to be using it at this point. There is a full discussion of all this along with plenty of examples in the docs.

    The primary purpose of Span<T> is to eliminate all the little string allocations that are commonly done when working with strings. For example if you need to get the first 4 characters of a string then the standard string functions allocate a new string to store that copy. The goal of Span is to eliminate the allocation. Many of the string functions have been updated to work with Span as well. Instead of allocating a new string the span simply provides a view into the existing string limited by the span size you wanted (e.g. 4). It is all about performance and memory management. Again, unless you understand all this then don't worry about Span right now. It is not going to impact your daily code. Refer to the linked document for more rationales and examples.

    The other types you mentioned are just generalizations and specializations over the same concept, a view into an existing set of data without allocating a new object.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 35,796 Reputation points

    only arrays of value types use contiguous memory. with arrays of objects, the contiguous memory is the pointers to the objects.

    Span<T> is not for low memory consumption, but rather low heap allocations. Span<> can be used to map already allocated memory or use the stack. Memory<> is generally for handling unmanned memory.

    If you do not fully understand memory allocation and ownership, then Span<>, and Memory<> are of little use to you.

    1 person found this answer helpful.
    0 comments No comments