Chapter 23. Span<T> and Memory<T>
The Span<T>
and Memory<T>
structs act as low-level façades over an array, string, or any contiguous block of managed or unmanaged memory. Their main purpose is to help with certain kinds of micro-optimizationâin particular, writing low-allocation code that minimizes managed memory allocations (thereby reducing the load on the garbage collector) without having to duplicate your code for different kinds of input. They also enable slicingâworking with a portion of an array, string, or memory block without creating a copy.
Span<T>
and Memory<T>
are particularly useful in performance hotspots, such as the ASP.NET Core processing pipeline or a JSON parser that serves an object database.
Note
Should you come across these types in an API and not need or care for their potential performance advantages, you can deal with them easily as follows:
When calling a method that expects a
Span<T>
,ReadOnlySpan<T>
,Memory<T>
, orReadOnlyMemory<T>
, pass in an array instead; that is,T[]
. (This works thanks to implicit conversion operators.)To convert from a span/memory to an array, call the
ToArray
method. And ifT
ischar
,ToString
will convert the span/memory into a string.
Specifically, Span<T>
does two things:
It provides a common array-like interface over managed arrays, strings, and pointer-backed memory. This gives you the freedom to employ stack-allocated and unmanaged memory to avoid garbage collection, without having to duplicate code or mess ...
Get C# 10 in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.