打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
比较C#中几种常见的复制字节数组方法的效率
using System;using System.Collections.Generic;using System.Diagnostics;using System.IO;namespace BenchmarkCopyArray{ class Program { private const int TestTimes = 10000000; 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 = 0; 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[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 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, 0); } public void TestArrayDotCopy() { var bytesNew = new byte[_sourceBytes.Length]; Array.Copy(_sourceBytes, 0, bytesNew, 0, _sourceBytes.Length); } public void TestBlockCopy() { var bytesNew = new byte[_sourceBytes.Length]; Buffer.BlockCopy(_sourceBytes, 0, bytesNew, 0, _sourceBytes.Length); } }}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
5天不再惧怕多线程——第一天 尝试Thread
MongoDB学习笔记(六) MongoDB索引用法和效率分析
第一天 Parallel的使用
.NET/C# 万能 HTTP 模拟请求框架
【C#】反射的用法及效率对比
UnityEvent与C#事件系统性能对比
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服