Introduction

In modern high-performance applications, reducing memory allocations and improving execution speed is critical. .NET 9 continues to enhance low-level memory handling using:

These features allow developers to write allocation-free, high-speed code, especially useful in:

Why These Concepts Matter

Traditional approaches (like arrays and strings) often:

Span and Memory solve this by working with stack or managed memory efficiently without copying data.

1. Span – Fast Stack-Based Memory Access

Key Points

Example

public static void SpanExample()
{
    int[] numbers = { 1, 2, 3, 4, 5 };

    Span<int> span = numbers;

    span[0] = 100;

    Console.WriteLine(numbers[0]); // Output: 100
}

Benefits

Limitations

Cannot be used in:

2. Memory – Heap-Friendly Alternative

Key Points

Example

public static async Task MemoryExample()
{
    int[] numbers = { 10, 20, 30 };

    Memory<int> memory = numbers;

    await Task.Delay(100);

    memory.Span[0] = 999;

    Console.WriteLine(numbers[0]); // Output: 999
}

Span vs Memory

3. ref struct – The Backbone

What is ref struct?

A ref struct:

Span itself is a ref struct.

public ref struct MyBuffer
{
    private Span<int> _data;

    public MyBuffer(Span<int> data)
    {
        _data = data;
    }

    public void SetFirst(int value)
    {
        _data[0] = value;
    }
}

Real-World Use Case

Scenario: High-Performance String Parsing

Traditional Approach

string data = "apple,banana,grape";
var parts = data.Split(',');

Creates multiple string allocations.

Optimized with Span

ReadOnlySpan<char> span = "apple,banana,grape".AsSpan();

int index = span.IndexOf(',');

var first = span.Slice(0, index);

Console.WriteLine(first.ToString()); // apple

No extra allocations until ToString().

Performance Impact

Using Span and Memory can:

When to Use What?

Common Mistakes

Interview Questions

Conclusion

In .NET 9, mastering Span, Memory, and ref struct gives you a huge performance advantage.

These are not beginner features — they are senior-level tools used in: