.NET Span<T> better performance

  • Array Copy
  • Span<T>
  • unsafe pointer
public int[] Data = Enumerable.Range(0, 10_000_000).ToArray();
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 |
  • 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).

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

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
Bnaya Eshet

Bnaya Eshet

More from Medium

The Facilis framework for dotnet core — the plan

GraphQL in Microservice Architecture with a demo (.NET 5 & Python3)

Martin Fowler’s Design Pattern Transaction Script in C# (With UI)

New Way of Hashing Data In .NET 5 and Later