Span in C#

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. Here is how it described:

“System.Span 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)

var intarray = new int[10];
Span<int> intspan = intarray;

or

var bytearray = new byte[10];
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[0] = 42;
sliced[1] = 43;
sliced[2] = 44;
Assert.Equal(42, sliced[0]);
Assert.Equal(43, sliced[1]);
Assert.Equal(44, sliced[2]);
Assert.Equal(bytearray[2], sliced[0]);
Assert.Equal(bytearray[3], sliced[1]);
Assert.Equal(bytearray[4], sliced[2]);
sliced[3] = 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 for example), I need more time to absorb it, but I wanted an initial searchable reference here.



Comment Section

Comments are closed.