usingSystem;usingSystem.Collections.Generic;usingSystem.Diagnostics;usingSystem.IO;namespaceBenchmarkCopyArray
{classProgram
{private const int TestTimes = 10000000;static voidMain()
{var testArrayCopy = newTestArrayCopy();
TestCopy(testArrayCopy.TestBinaryReader,"Binary.ReadBytes");
TestCopy(testArrayCopy.TestConvertToList,"ConvertToList");
TestCopy(testArrayCopy.TestArrayDotCopy,"Array.Copy");
TestCopy(testArrayCopy.TestBlockCopy,"Buffer.BlockCopy");
Console.Read();
}private static void TestCopy(Action testMethod, stringmethodName)
{var stopWatch = newStopwatch();
stopWatch.Start();for (int i = 0; i < TestTimes; i++)
{
testMethod();
}
testMethod();
stopWatch.Stop();
Console.WriteLine("{0}: {1} seconds, {2}.", methodName, stopWatch.Elapsed.Seconds, stopWatch.Elapsed.Milliseconds);
}
}classTestArrayCopy
{private readonly byte[] _sourceBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};public voidTestBinaryReader()
{var binaryReader = new BinaryReader(newMemoryStream(_sourceBytes));
binaryReader.ReadBytes(_sourceBytes.Length);
}public voidTestConvertToList()
{
IList bytesSourceList = new List(_sourceBytes);var bytesNew = new byte[_sourceBytes.Length];
bytesSourceList.CopyTo(bytesNew,0);
}public voidTestArrayDotCopy()
{var bytesNew = new byte[_sourceBytes.Length];
Array.Copy(_sourceBytes,0, bytesNew, 0, _sourceBytes.Length);
}public voidTestBlockCopy()
{var bytesNew = new byte[_sourceBytes.Length];
Buffer.BlockCopy(_sourceBytes,0, bytesNew, 0, _sourceBytes.Length);
}
}
}