Understanding Span

C# 7.2 has introduced Span<T> along with a some language features so developers can better optimize code when using structs / value types.

To goal of this post is to (instead of explaining) present a collection of articles and blog posts that help the reader to fully understand these new features.

Let's start by the new features. The following article shall explain

  • in keyword

  • ref readonly

  • readonly struct

  • ref struct

It also mentions Span<T> and ReadOnlySpan<T>. The compiler rules on seems a bit odd at first sight, and poses several questions (why do we need these? how does this work? is there a memory copy happening? how do we avoid allocation? how do we avoid the pressure on GC?)

The second article gives us some of the answers for Span<T>

It helps answering the use-cases for Span<T> (avoiding string allocations, parsing, buffer reading, etc.) It also introduces a 'Struct Tearing' which is a threading related issue. The ' Stack only paragraph might help to understand the reasons behind it being stack only, but for me it just posed more questions (how does managed point work with a ref T field? how does GC track this reference? what if the pointed object moved by the GC? how does the compiler make sure on these rules? how is this different to TypedReference?)

TypedReference itself is explained by Sasha Goldshtein's Pro .Net Performance book.

After another round of searching I reached to Vladimir Sadov blog which gives answers to the rest of the questions.

Let's start with:

  • Managed pointers

  • Explaining most of the above questions, then continued to ref returns and limitations (gives a great comparison to c++ and go): mustoverride.com/ref-returns-and-locals/

  • Continuing to mustoverride.com/ref-locals_single-assignment/ which explains the issues over ref locals and compares it to TypedReference.

  • Finally mustoverride.com/safe-to-return/ answers some further restrictions related to memory handling.