0009 Using Span and Memory for High-Performance Code

Span<T> and Memory<T> are high-performance types introduced in C# 7.2 for working with contiguous memory regions (e.g., arrays, strings, or stack-allocated memory). They help reduce allocations and improve performance in scenarios like parsing, slicing, and processing large datasets.

What is Span<T>?

Example: Slicing an Array

int[] array = { 1, 2, 3, 4, 5 };
Span<int> slice = array.AsSpan(1, 3); // Points to { 2, 3, 4 }

foreach (var item in slice)
{
    Console.WriteLine(item); // Output: 2, 3, 4
}

What is Memory<T>?

Example: Using Memory<T> in Async Code

async Task ProcessDataAsync(Memory<int> data)
{
    await Task.Delay(100); // Simulate async work
    foreach (var item in data.Span)
    {
        Console.WriteLine(item);
    }
}

// Usage
int[] array = { 1, 2, 3, 4, 5 };
await ProcessDataAsync(array.AsMemory(1, 3)); // Output: 2, 3, 4

Key Benefits:

  1. Performance:

  2. Memory Safety:

  3. Flexibility:


Use Cases:

  1. Parsing Strings:

string input = "123,456,789";
ReadOnlySpan<char> span = input.AsSpan();
int index = span.IndexOf(',');
ReadOnlySpan<char> firstNumber = span.Slice(0, index); // Points to "123"
  1. Processing Large Data:

  2. Stack Allocation: