C#中copy的效率问题,很不错,学习!
来源:互联网 发布:linux中mount命令 编辑:程序博客网 时间:2024/06/06 18:12
在日常编程过程中,我们可能经常需要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 = 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);
- }
- }
- }
运行结果如下:
0 0
- C#中copy的效率问题,很不错,学习!
- C# 数组Copy的效率问题
- C#中Delegate的效率问题
- C#中循环结构的效率问题
- C#中循环结构的效率问题
- 看到一篇有关SQL效率问题的文章,觉得很不错
- 在ruby学习中,很不错的书籍
- C#中Dictionary<Key,Value>中[]操作的效率问题
- C# 中Parse 和TryParse的效率问题
- c#的委托函数很不错
- 服务器端沾包处理的copy效率问题
- 很不错的JAVA学习笔记
- 很不错的JAVA学习笔记
- 很不错的Linux学习网站
- 一个很不错的android学习网站
- 一个很不错的lua学习实例
- 一个很不错的学习网站
- 感觉很不错的学习网站
- [已解决] PopupWindow 弹出后点击屏幕任何地方都没有反应了,PopupWindow弹出之后,怎么点击外面取消不了
- UIView绘制机制(转)
- Github使用
- NSDate和NSString相互转换
- 如何阅读代码
- C#中copy的效率问题,很不错,学习!
- 第一部分:操作系统概述
- VS2010项目属性的默认包含路径设置方法
- CentOS7下三步安装单点OpenStack【KVM、VMwareOK】
- 什么是数据持久化?
- 替换空格
- 第二部分:进程管理
- UITableViewCell 选中时的颜色设置
- JavaScript学习笔记六:Map和Set