.NET Span<T> better performance

Span<T> is a new type which will be available on .NET Core 2.1.

To simplify it, you may think at it like a Value Type array 
which can be slice into sub unit without memory allocation.

On the following section, I would like to present few benchmarks and code samples.

The benchmark compare the performance of slicing Array using:

  • Array Copy
  • Span<T>
  • unsafe pointer

The benchmarks available at GitHub (it’s using BenchmarkDotNet).

All benchmarks are using the following array:

public int[] Data = Enumerable.Range(0, 10_000_000).ToArray();

The classic array manipulation using is:

The Span<T> is using:

The Pointer is using:

The results was:

Method  |Mean         |Scaled |Rank   |Allocated  |
------- |------------:|------:|------:|----------:|
Array | 4,966.5 us | 1.00 | 3 | 4032 B |
Span | 162.9 us | 0.03 | 1 | 0 B |
Pointer | 175.3 us | 0.04 | 2 | 0 B |

Some interesting facts on Span<T>:

  • Add System.Memory NuGet in order you get reference to it.
  • It cannot be allocate on the Heap,
    therefore, cannot be member of a class.
  • It can be member of a ref struct.
  • It shine when you have to do string manipulations like SubString
    for example: 
    “AbCD”.AsSpan() returns ReadOnlySpan<char>
     — — — — — — — — — — — — — — — — — — — — — — — 
    this means that you can use “ABCD”.AsSpan().Slice(2,1) 
    instead of “ABCD”.Substring(2,1).

You can read more about it in Stephen Toub’s Paper.