[原文链接]

在日常编程过程中,我们可能经常需要Copy各种数组,一般来说有以下几种常见的方法:Array.Copy,IList<T>.Copy,BinaryReader.ReadBytes,Buffer.BlockCopy,以及System.Buffer.memcpyimpl,由于最后一种需要使用指针,所以本文不引入该方法。

本次测试,使用以上前4种方法,各运行1000万次,观察结果。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO; namespace BenchmarkCopyArray
{
class Program
{
private const int TestTimes = ;
static void Main()
{
var testArrayCopy = new TestArrayCopy();
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, string methodName)
{
var stopWatch = new Stopwatch();
stopWatch.Start();
for (int i = ; i < TestTimes; i++)
{
testMethod();
}
testMethod();
stopWatch.Stop();
Console.WriteLine("{0}: {1} seconds, {2}.", methodName, stopWatch.Elapsed.Seconds, stopWatch.Elapsed.Milliseconds);
}
} class TestArrayCopy
{
private readonly byte[] _sourceBytes = new byte[] { , , , , , , , , , }; public void TestBinaryReader()
{
var binaryReader = new BinaryReader(new MemoryStream(_sourceBytes));
binaryReader.ReadBytes(_sourceBytes.Length);
} public void TestConvertToList()
{
IList<byte> bytesSourceList = new List<byte>(_sourceBytes);
var bytesNew = new byte[_sourceBytes.Length];
bytesSourceList.CopyTo(bytesNew, );
} public void TestArrayDotCopy()
{
var bytesNew = new byte[_sourceBytes.Length];
Array.Copy(_sourceBytes, , bytesNew, , _sourceBytes.Length);
} public void TestBlockCopy()
{
var bytesNew = new byte[_sourceBytes.Length];
Buffer.BlockCopy(_sourceBytes, , bytesNew, , _sourceBytes.Length);
}
}
}

运行结果如下:

最新文章

  1. SAP CRM 树视图(TREE VIEW)
  2. Android 解析聊天表情的笔记
  3. win7 下安装RVCT
  4. ASP.NET MVC分页组件MvcPager 2.0版发布暨网站全新改版
  5. 读javascript高级程序设计15-Ajax,CORS,JSONP,Img Ping
  6. android:Faild to install,你的主机中的软件终止了一个连接错误解决
  7. JSP环境配置
  8. Python3学习之一环境搭建
  9. justAP1.3.0版发布了
  10. Android插件化开发---执行未安装apk中的Service
  11. tabbar颜色与文字大小,状态栏样式
  12. 我的webstorm 使用总结
  13. 基于mysql的一些sql语法
  14. package.json 里的 dependencies和devDependencies区别
  15. Angular4中使用后台去数据,Swiper不能滑动的解决方法(一)
  16. 20180519001 - DataTable Group by功能参考
  17. Cache 和 Buffer 都是缓存,主要区别是什么?【转】
  18. P3721 [AH2017/HNOI2017]单旋
  19. main.cpp
  20. java的list集合操作List&lt;T&gt;转化List&lt;Long&gt;

热门文章

  1. Java入门 第一季第五章 编程练习解析
  2. react-container-query
  3. 安装PyQt5和Eric6
  4. sql server 笔记1--case、WAITFOR、TRY CATCH
  5. my-small.cnf my-medium.cnf my-large.cnf my-huge.cnf
  6. ASP.NET for WebApi
  7. 将项目上传到GitHub
  8. java8--NIO(java疯狂讲义3复习笔记)
  9. ranlib
  10. linux网络socket 接口转