.NET has been getting so many performance upgrades and one of the main reason behind that is Span<T>. Let me explain what a Span is and how it works.

What is Span<T>

Span<T> is a new value type introduced in .NET Core and .NET Standard (yes, you can use it in .NET Framework by installing the package System.Memory) that provides a type-safe and memory-safe representation of a contiguous region of arbitrary memory. In simple terms, imagine you have a big string of colorful beads, and each bead represents a piece of information. Now, suppose you want to play with just a part of this string—let’s say beads number 5 through 10.

Instead of cutting the string and making a new, smaller one, you simply point to that section and say, “I’m going to use this part right here!” This way, you don’t have to create anything new or change the original string.

Key Features

  • Type Safety: Ensures that all elements within the span are of the same type T.
  • Memory Safety: Bounds checking prevents access outside the allocated memory region.
  • No Heap Allocation: Span<T> itself does not allocate memory on the heap, reducing garbage collection overhead.

Examples

var date = SpanExamples.ParseDateFromStringSpan("monday:2020/1/1");

public static DateTime ParseDateFromStringSpan(string text)
{
    var span = text.AsSpan();

    ReadOnlySpan<char> day = span.Slice(span.IndexOf(':') + 1);

    DateTime date = DateTime.Parse(day);

    return date;
}

In the example above we can extract a date from a string without allocating substrings! Let’s see another short example.

var number = SpanExamples.ExtractNumberWithSpan("123:text");

public static int ExtractNumberWithSpan(string text)
{
    var span = text.AsSpan();
    ReadOnlySpan<char> number = span[..span.IndexOf(':')];
    return int.Parse(number);
}

Why Use Span<T>

  • Performance: Minimizes memory allocations and copying, leading to faster code execution.
  • Flexibility: Can work with arrays, strings, and generally stack-allocated memory.
  • Safety: Provides bounds checking and avoids unsafe code blocks.

Conclusion

Span<T> is a powerful addition to the .NET ecosystem, offering developers more control over memory management while maintaining safety and performance. You should now understand why more and more things are using Spans inside .NET.

Affiliate promo

If you love learning new stuff and want to support me, consider buying a course from Dometrain using this link: Browse courses – Dometrain. Thank you!

Leave a comment

Trending