.NET: Array-Slicing Using Span<T>

Comparing the performance of slicing an array using Array Copy, Span<T>, and unsafe pointer.

Bnaya Eshet
Cloud Native Daily

--

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

To simplify it, you may think of it like a Value Type array
which can be sliced into sub-units without memory allocation.

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

The benchmark compares the performance of slicing Array using:

  • Array Copy
  • Span<T>
  • unsafe pointer

The benchmarks are available on 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 were:

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 a reference to it.
  • It cannot be allocated on the Heap,
    therefore, cannot be a member of a class.
  • It can be a member of a ref struct.
  • It shines 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.

--

--