无聊做了如题的一个算法的优劣性能比较,由于很多人都只关心结果,那么我先贴出结果如下:
由于我的测试数据量比较小,只能得出Array.Copy()和Buffer.BlockCopy()方法性能要好于Contact(),这个不用比较也能想到,如果想知道前两个谁的性能更好,
有兴趣的可以修改源码中的测试数据量就可以了。
测试源码如下:
static int len1 = 1470; static int len2 = 906; static byte[] bytes0 = new byte[len1]; static byte[] bytes1 = new byte[len2]; static void Main(string[] args) { // Uses the second Core or Processor for the Test Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(1); Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High; // Prevents "Normal" Threads Thread.CurrentThread.Priority = ThreadPriority.Highest; Stopwatch sw = new Stopwatch(); byte[] resultBytes = null; InitBytes(); //test sw.Reset(); sw.Start(); while (sw.ElapsedMilliseconds < 1200) // A Warmup of 1000-1500 mS // stabilizes the CPU cache and pipeline. { resultBytes = Contact(bytes0, bytes1); // Warmup } sw.Stop(); for (int i = 0; i < 10; i++) { sw.Reset(); sw.Start(); resultBytes = Contact(bytes0, bytes1); sw.Stop(); Console.WriteLine("Contact Ticks: {0} Time: {1} ms", sw.ElapsedTicks, sw.ElapsedMilliseconds); } sw.Reset(); sw.Start(); while (sw.ElapsedMilliseconds < 1200) // A Warmup of 1000-1500 mS // stabilizes the CPU cache and pipeline. { resultBytes = BufferCopy(bytes0, bytes1); // Warmup } sw.Stop(); for (int i = 0; i < 10; i++) { sw.Reset(); sw.Start(); resultBytes = BufferCopy(bytes0, bytes1); sw.Stop(); Console.WriteLine("BufferCopy Ticks: {0} Time: {1} ms", sw.ElapsedTicks, sw.ElapsedMilliseconds); } sw.Reset(); sw.Start(); while (sw.ElapsedMilliseconds < 1200) // A Warmup of 1000-1500 mS // stabilizes the CPU cache and pipeline. { resultBytes = ArrayCopy(bytes0, bytes1); // Warmup } sw.Stop(); for (int i = 0; i < 10; i++) { sw.Reset(); sw.Start(); resultBytes = ArrayCopy(bytes0, bytes1); sw.Stop(); Console.WriteLine("ArrayCopy Ticks: {0} Time: {1} ms ", sw.ElapsedTicks, sw.ElapsedMilliseconds); } Console.ReadKey(); } static void InitBytes() { for(int i=0;i