获取字节数组的子数组

3

在C#中,我如何获取字节数组的子数组,例如:

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

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

有多种选项可供选择,比如使用Array.Copy、ArraySegment、LINQ(Skip和Take)等等。从性能的角度来看,哪种方法最好呢?


这些字节的来源是什么?数组有多大?您可能会发现流类很有用。 - ne1410s
5
从性能角度来看,什么是最佳解决方案?你真的认为这会成为应用程序性能的瓶颈吗?实现良好性能的最佳方法是设定性能目标。然后,将这些目标放在一边,编写简单、清晰、易于理解的代码。接下来,测量性能。如果达到了目标,工作完成,转移到下一个任务。如果没有达到目标,则分离出性能瓶颈所在的位置。它不太可能是这里。 - Damien_The_Unbeliever
3个回答

14

简单性能测试:

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 会出现问题。


我们应该在Linq测试中执行 sw.Restart(),否则sw.ElapsedMilliseconds也会包括Array.Copy()的毫秒数。 - Luis E. Fraguada
在这里添加了 Buffer.Copy() 测试:https://gist.github.com/fraguada/301fe31b939e6889514969cb1bbec37c - Luis E. Fraguada

10

1
对于@General-Doomer发布的测试,Buffer.BlockCopy()确实更快。我已经添加了一个测试Buffer.BlockCopy()ArraySegment<int>().ToArray()的gist:https://gist.github.com/fraguada/301fe31b939e6889514969cb1bbec37c - Luis E. Fraguada

7

使用 Array.Copy

示例:

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

格式:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接