在C#中,我如何获得像这样的子字节数组
byte[] arrByte1 = {11,22,33,44,55,66}
我需要引用两个字节的子数组,如33和44值。
我在C#中找到了多个选项,如Array.Copy,ArraySegment,LINQ(Skip and Take)。从性能的角度来看,最佳解决方案是什么?
答案 0 :(得分:9)
简易性能测试:
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有麻烦。
答案 1 :(得分:2)
示例:
int[] target=new int[2];
Array.Copy(arrByte1,2, target,0, 2);
格式:
Array.Copy(Source,Source index, target,target index, length);
答案 2 :(得分:2)
Buffer.BlockCopy比Array.Copy快。