C# 获取字节的子数组
在C#中,如何获得这样的字节子数组C# 获取字节的子数组,c#,arrays,bytearray,C#,Arrays,Bytearray,在C#中,如何获得这样的字节子数组 byte[]arrByte1={11,22,33,44,55,66} 我需要引用两个字节的子数组,比如33和44值 我发现有很多选项,比如C#中的Array.Copy、ArraySegment、LINQ(Skip-and-Take)。从性能角度来看,什么是最好的解决方案?使用 例如: int[] target=new int[2]; Array.Copy(arrByte1,2, target,0, 2); 格式: Array.Copy(Source,So
byte[]arrByte1={11,22,33,44,55,66}
我需要引用两个字节的子数组,比如33和44值
我发现有很多选项,比如C#中的Array.Copy、ArraySegment、LINQ(Skip-and-Take)。从性能角度来看,什么是最好的解决方案?使用 例如:
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);
}
大数据性能测试:
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);
}
如您所见,在大数据上,linq有问题。比数组快。复制字节数组。这些字节的来源是什么?阵列有多大?您可能会发现流类很有用..“从性能角度来看,什么是最好的解决方案”-您真的认为这会成为应用程序性能的瓶颈吗?实现良好绩效的最佳方式是设定绩效目标。然后,把这些目标放在一边,编写简单、清晰、易懂的代码。然后,测量性能。如果它达到了目标,完成了工作,并进入下一个任务。如果达不到目标,请找出性能瓶颈所在。不太可能在这里。我们应该对Linq测试执行
sw.Restart()
,否则sw.elapsedmillesons
还包括Array.Copy()
毫秒。在这里添加Buffer.Copy()
测试:对于@General Doomer发布的测试,Buffer.BlockCopy()
确实更快。我添加了一个要点,测试了Buffer.BlockCopy()
和ArraySegment().ToArray()
:
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