测试复制数组:Array.Copy与Buffer.BlockCopy的性能(运行时间)
数组元素复制可以使用两个方法:
1.Array.Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)
2.Buffer.BlockCopy(Array src, int srcOffset, Array dst, int dstOffset, int count)
下面测试两者的性能
新建控制台应用程序CopyArrayPerformanceDemo。
测试源程序如下:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CopyArrayPerformanceDemo
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
Action<Array, int, Array, int, int> ActionCopy = Array.Copy;
TestCopyArray($"Array.Copy 第({i + 1})次", ActionCopy);
ActionCopy = Buffer.BlockCopy;
TestCopyArray($"Buffer.BlockCopy 第({i + 1})次", ActionCopy);
Console.WriteLine();
}
Console.ReadLine();
}
/// <summary>
/// 测试复制数组
/// </summary>
/// <param name="categoyTest">使用的方法描述</param>
/// <param name="ActionCopy">所使用的复制数组的方法</param>
static void TestCopyArray(string categoyTest, Action<Array, int, Array, int, int> ActionCopy)
{
byte[] source = new byte[1024 * 1024 * 10]; //10MB
int offset = 1024 * 1024 * 5;
int length = 1024 * 1024 * 5;
byte[] target = new byte[length];
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < 100; i++)
{
ActionCopy(source, offset, target, 0, length);
//Buffer.BlockCopy(source, offset, target, 0, length);
//Array.Copy(source, offset, target, 0, length);
}
watch.Stop();
Console.WriteLine($"使用【{categoyTest}】复制10M数组的内容,花费时间【{watch.ElapsedMilliseconds}】ms");
}
}
}