Chapter 24. 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:
Pass in an array when calling a method that expects a
Span<T>,ReadOnlySpan<T>,Memory<T>orReadOnlyMemory<T>instead; that is,T[]. (This works thanks to implicit conversion operators.)Call the
ToArraymethod to convert from a span/memory to an array. And ifTischar,ToStringwill 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 with pointers.
It allows slicing: exposing reusable ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access