Skip to Content
C# 9.0 in a Nutshell
book

C# 9.0 in a Nutshell

by Joseph Albahari
February 2021
Intermediate to advanced
1060 pages
26h 28m
English
O'Reilly Media, Inc.
Content preview from C# 9.0 in a Nutshell

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>, or ReadOnlyMemory<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 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 ...

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.
Start your free trial

You might also like

C# 8.0 in a Nutshell

C# 8.0 in a Nutshell

Joseph Albahari, Eric Johannsen
C# 10 in a Nutshell

C# 10 in a Nutshell

Joseph Albahari
Async in C# 5.0

Async in C# 5.0

Alex Davies

Publisher Resources

ISBN: 9781098100957Errata PageSupplemental Content