在尝试新功能Span<byte>和Memory<byte>功能时,我发现Memory<byte>与其他与字节数组交互的方法相比,使用解析二进制数据的速度比我预期的要慢得多。
我设置了一个基准测试套件,使用多种方法从数组中读取单个整数,发现内存是最慢的。正如预期的那样,它比 Span 慢,但令人惊讶的是,它也比直接使用数组慢,也比我自己开发的我期望 Memory 内部相似的版本慢。
// Suite of tests comparing various ways to read an offset int from an array
public class BinaryTests
{
static byte[] arr = new byte[] { 0, 1, 2, 3, 4 };
static Memory<byte> mem = arr.AsMemory();
static HomegrownMemory memTest = new HomegrownMemory(arr);
[Benchmark]
public int StraightArrayBitConverter()
{
return BitConverter.ToInt32(arr, 1);
}
[Benchmark]
public int MemorySlice()
{
return BinaryPrimitives.ReadInt32LittleEndian(mem.Slice(1).Span);
}
[Benchmark]
public int MemorySliceToSize()
{
return BinaryPrimitives.ReadInt32LittleEndian(mem.Slice(1, 4).Span); …Run Code Online (Sandbox Code Playgroud) c# ×1