.NET Span<T> better performance

bnaya eshet
May 12, 2018 · 2 min read

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.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store