项目中需要频繁处理byte[],之前复制byte[]一直用的是array.skip(x).take(x).ToArray(),因为它写起来方便。
今天突然想起复制数组还有个方法Array.Copy(),不知道哪个方法更快一些,就写了代码进行测试。
测试代码:
MemoryStream stream = FileIO.GetFile(@"C:/Users/Admin/Desktop/000.psd"); byte[] byts = stream.ToArray(); stream.Close(); int i = 0; int n = 6000; Console.Out.WriteLine("开始测试"); Stopwatch sw = new Stopwatch(); sw.Start(); while (i < byts.Length) { try { var t = byts.Skip(i).Take(n).ToArray(); i += n; }catch(ArgumentException e) { i += n; } } sw.Stop(); Console.Out.WriteLine("/tTake总用时:{0}秒", sw.ElapsedMilliseconds * 0.001); i = 0; sw.Restart(); while(i < byts.Length) { try { byte[] t = new byte[n]; Array.Copy(byts, i, t, 0, n); i += n; }catch(ArgumentException e) { i += n; } } sw.Stop(); Console.Out.WriteLine("/tCopy总用时:{0}秒", sw.ElapsedMilliseconds * 0.001);
测试结果:
Take总用时:27.344秒 Copy总用时:0.035秒
原创文章,作者:bd101bd101,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/277047.html