小编maz*_*301的帖子

为什么Span比内存快10倍

我有字节数组

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];
}
Run Code Online (Sandbox Code Playgroud)

基准测试结果

我不明白为什么 Span 比内存快 10 倍。从我的角度来看,Span 是在堆栈上分配的,但它指向堆上的数据(在我的例子中)。内存是在堆上分配的,这只是我在这里看到的一个区别。我的问题是为什么 Span 这么快?我读过有关 ref structs 的内容,但不明白它是如何工作的。

c# optimization performance stack

2
推荐指数
1
解决办法
777
查看次数

标签 统计

c# ×1

optimization ×1

performance ×1

stack ×1