测试 Array.ConstrainedCopy
和 List.AddRange 两种拼接字节数组的效率
Array.ConstrainedCopy 要快一些
在 10M 字节前加入两个字节
Array.ConstrainedCopy 用时5ms
List.AddRange 用时21ms
byte[] one = new byte[2] { 0x1, 0x2 };
byte[] two = new byte[10000000];
for (int i = 0; i < two.Length; i++)
{
two[i] = (byte)i;
}
Stopwatch sw = new Stopwatch();
sw.Start();
byte[] three = new byte[two.Length + 2];
Array.ConstrainedCopy(one, 0, three, 0, one.Length);
Array.ConstrainedCopy(two, 0, three, 2, two.Length);
Console.WriteLine(three[256]);
sw.Stop();
Console.WriteLine("耗时:" + sw.ElapsedMilliseconds + "ms");
Console.WriteLine("耗时:" + sw.Elapsed.TotalSeconds + "s");
sw.Start();
List<byte> data = new List<byte>();
data.AddRange(one);
data.AddRange(two);
byte[] four = data.ToArray();
Console.WriteLine(four[256]);
sw.Stop();
Console.WriteLine("耗时:" + sw.ElapsedMilliseconds + "ms");
Console.WriteLine("耗时:" + sw.Elapsed.TotalSeconds + "s");
Array 占用的内存较小 时间换空间
Array.ConstrainedCopy 占用的内存较大 空间换时间