比较C#中几种常见的复制字节数组方法的效率[转]
2024-10-20 00:31:33
在日常编程过程中,我们可能经常需要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);
}
}
}
运行结果如下:
最新文章
- SAP CRM 树视图(TREE VIEW)
- Android 解析聊天表情的笔记
- win7 下安装RVCT
- ASP.NET MVC分页组件MvcPager 2.0版发布暨网站全新改版
- 读javascript高级程序设计15-Ajax,CORS,JSONP,Img Ping
- android:Faild to install,你的主机中的软件终止了一个连接错误解决
- JSP环境配置
- Python3学习之一环境搭建
- justAP1.3.0版发布了
- Android插件化开发---执行未安装apk中的Service
- tabbar颜色与文字大小,状态栏样式
- 我的webstorm 使用总结
- 基于mysql的一些sql语法
- package.json 里的 dependencies和devDependencies区别
- Angular4中使用后台去数据,Swiper不能滑动的解决方法(一)
- 20180519001 - DataTable Group by功能参考
- Cache 和 Buffer 都是缓存,主要区别是什么?【转】
- P3721 [AH2017/HNOI2017]单旋
- main.cpp
- java的list集合操作List<;T>;转化List<;Long>;