I just got through reading Stephen Toub’s “All about Span: Exploring a new .NET Mainstay”, it is comprehensive, brilliant and it feels like one of those seminal pieces we will be referencing for years. It introduces a new type that is set to transform the way we approach sorting and it starts with System.Span<T>. Here is how it described:
“System.Span<T> is a new value type at the heart of .NET. It enables the representation of contiguous regions of arbitrary memory, regardless of whether that memory is associated with a managed object, is provided by native code via interop, or is on the stack.”
So this means, for example, I can convert any array (as in T) into a Span (as in Span<T>)
var intarray = new int; Span<int> intspan = intarray;
var bytearray = new byte; Span<byte> bytespan = byterarray;
You get the picture … but why is this important? Now that we have it in Span we can efficiently reference any part of the array without quietly making copies (allocations).
Span<byte> sliced = bytespan.Slice(start: 2, length: 3); sliced = 42; sliced = 43; sliced = 44; Assert.Equal(42, sliced); Assert.Equal(43, sliced); Assert.Equal(44, sliced); Assert.Equal(bytearray, sliced); Assert.Equal(bytearray, sliced); Assert.Equal(bytearray, sliced); sliced = 44; // IndexOutOfRangeException
In above example I am changing the original array I did not need to make copies to deal with subsets of the original array. I spend a lot of time analyzing hang dumps and it might honestly surprise you how inefficiently we code even with the best of intentions.
There is much more to the original article (Memory<T> for example), I need more time to absorb it, but I wanted an initial searchable reference here.