Why is Span faster than memory in 10 times
13:06 08 Apr 2023

I have array of bytes

private byte[] _data;


[Benchmark()]
public void SpanTest()
{
    var temp = _data.AsSpan();
    var length = BitConverter.ToInt32(temp.Slice(0, 4));
    var buffData = temp.Slice(4, length);
    var s = buffData[0];
}

[Benchmark()]
public async Task MemoryTest()
{
    var temp = _data.AsMemory();
    var length = BitConverter.ToInt32(temp.Slice(0, 4).Span);
    var buffData = temp.Slice(4, length);
    var s = buffData.Span[0];
}

Results of benchmark

I can't understand why Span is faster than memory like in 10 times. From my perspective, Span is allocated on the stack but it points to the data on the heap (in my case). Memory is allocated on the heap and that's only one difference that I see here. My question is why Span is so fast? I have read about ref structs but didn't understand how it works.

c# performance optimization stack