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> or ReadOnly​Memory<T> instead; that is, T[]. (This works thanks to implicit conversion operators.)

  • Call the ToArray method to convert from a span/memory to an array. And if T is char, 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 with pointers.

  • It allows slicing: exposing reusable ...

Get C# 8.0 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.