.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:

The classic array manipulation using is:

The Span<T> is using:

The Pointer is using:

The results was:

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.

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