本次测试主要使用Array和Buffer对象的数组复制方法进行效率比较。
对于内存复制,由于要使用Unsafe代码,暂时没有测试。
static void Test(int _size)
{
Console.WriteLine();
Console.WriteLine();
byte[] _src = new byte[_size];
byte[] _dst = new byte[_size];
//_src[0] = 1;
//_src[1] = 2;
//_src[_size - 2] = 254;
//_src[_size - 1] = 255;
for (int i = 0; i < _size; i++)
{
_src[i] = (byte)(i % 256);
}
System.Diagnostics.Stopwatch _sw;
_sw = new System.Diagnostics.Stopwatch();
//方式一;
_sw.Reset();
_sw.Start();
Array.Copy(_src, 0, _dst, 0, _src.Length);
_sw.Stop();
Console.WriteLine("数量:{0},Array.Copy 用时:{1} ", _size, _sw.ElapsedTicks);
//方式二;
_sw.Reset();
_sw.Start();
Array.ConstrainedCopy(_src, 0, _dst, 0, _src.Length);
_sw.Stop();
Console.WriteLine("数量:{0},Array.ConstrainedCopy 用时:{1} ", _size, _sw.ElapsedTicks);
//方式三;
_sw.Reset();
_sw.Start();
System.Buffer.BlockCopy(_src, 0, _dst, 0, _src.Length);
_sw.Stop();
Console.WriteLine("数量:{0},Buffer.BlockCopy 用时:{1} ", _size, _sw.ElapsedTicks);
//方式四 内存操作
//这个需要unsafe代码,将数组转换为IntPtr,这里不测试;
//_sw.Start();
//IntPtr _p1 = ArrayToIntptr(_src);
//System.Runtime.InteropServices.Marshal.Copy(_src, 0, _p1, _src.Length);
//_sw.Stop();
//Console.WriteLine("Buffer.BlockCopy 用时: " + _sw.ElapsedTicks.ToString());
}
//外部调用;
Test(10000);
Test(100000);
Test(1000000);
测试结果如下:
-----------------------------------------------------------------------------------
数量:10000,Array.Copy 用时:19
数量:10000,Array.ConstrainedCopy 用时:17
数量:10000,Buffer.BlockCopy 用时:6
数量:100000,Array.Copy 用时:315
数量:100000,Array.ConstrainedCopy 用时:67
数量:100000,Buffer.BlockCopy 用时:59
数量:1000000,Array.Copy 用时:2889
数量:1000000,Array.ConstrainedCopy 用时:569
数量:1000000,Buffer.BlockCopy 用时:534