获取字节子数组

Get subarray of byte

在 C# 中,如何获得这样的字节子数组

byte[] arrByte1 = {11,22,33,44,55,66}

我需要参考两个字节的子数组,例如 33 和 44 值。

我发现有多个选项,例如 Array.Copy、ArraySegment、C# 中的 LINQ(Skip and Take)。从性能的角度来看,最好的解决方案是什么?

使用Array.Copy

示例:

int[] target=new int[2];
Array.Copy(arrByte1,2, target,0, 2);

格式:

  Array.Copy(Source,Source index, target,target index, length);

简单的性能测试:

public void Test()
{
    const int MAX = 1000000;

    byte[] arrByte1 = { 11, 22, 33, 44, 55, 66 };
    byte[] arrByte2 = new byte[2];
    Stopwatch sw = new Stopwatch();

    // Array.Copy
    sw.Start();
    for (int i = 0; i < MAX; i++)
    {
        Array.Copy(arrByte1, 2, arrByte2, 0, 2);
    }
    sw.Stop();
    Console.WriteLine("Array.Copy: {0}ms", sw.ElapsedMilliseconds);

    // Linq
    sw.Restart();
    for (int i = 0; i < MAX; i++)
    {
        arrByte2 = arrByte1.Skip(2).Take(2).ToArray();
    }
    sw.Stop();
    Console.WriteLine("Linq: {0}ms", sw.ElapsedMilliseconds);
}

结果:

Array.Copy: 28ms
Linq: 189ms

大数据性能测试:

public void Test()
{
    const int MAX = 1000000;

    int[] arrByte1 = Enumerable.Range(0, 1000).ToArray();
    int[] arrByte2 = new int[500];
    Stopwatch sw = new Stopwatch();

    // Array.Copy
    sw.Start();
    for (int i = 0; i < MAX; i++)
    {
        Array.Copy(arrByte1, 500, arrByte2, 0, 500);
    }
    sw.Stop();
    Console.WriteLine("Array.Copy: {0}ms", sw.ElapsedMilliseconds);

    // Linq
    sw.Restart();
    for (int i = 0; i < MAX; i++)
    {
        arrByte2 = arrByte1.Skip(500).Take(500).ToArray();
    }
    sw.Stop();
    Console.WriteLine("Linq: {0}ms", sw.ElapsedMilliseconds);
}

结果:

Array.Copy: 186ms
Linq: 12666ms

如你所见,在大数据上linq有问题。

对于字节数组,

Buffer.BlockCopy 比 Array.Copy 快。