得到字节的子数组

Ank*_*dra 1 c# arrays bytearray

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

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

我需要引用两个字节的子数组,如33和44值.

我在C#中找到了多个选项,如Array.Copy,ArraySegment,LINQ(Skip and Take).从性能的角度来看,最佳解决方案是什么?

Gen*_*mer 10

简易性能测试:

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

结果:

Array.Copy: 28ms
Linq: 189ms
Run Code Online (Sandbox Code Playgroud)

对大数据的性能测试:

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

结果:

Array.Copy: 186ms
Linq: 12666ms
Run Code Online (Sandbox Code Playgroud)

如你所见,在大数据上linq有麻烦.


Nul*_*ter 7

使用Array.Copy

例子:

int[] target = new int[2];
Array.Copy(arrByte1, 2, target, 0, 2);
Run Code Online (Sandbox Code Playgroud)

格式:

Array.Copy(source, source index, target, target index, length);
Run Code Online (Sandbox Code Playgroud)


Sim*_*les 7

对于字节数组,Buffer.BlockCopy比 Array.Copy 快。