比较C#中几种常见的复制字节数组方法的效率[转]
2015-03-28 07:57
681 查看
[原文链接]
在日常编程过程中,我们可能经常需要Copy各种数组,一般来说有以下几种常见的方法:Array.Copy,IList<T>.Copy,BinaryReader.ReadBytes,Buffer.BlockCopy,以及System.Buffer.memcpyimpl,由于最后一种需要使用指针,所以本文不引入该方法。
本次测试,使用以上前4种方法,各运行1000万次,观察结果。
运行结果如下:
在日常编程过程中,我们可能经常需要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); } } }
运行结果如下:
![](http://images.cnitblog.com/blog2015/701910/201503/280756192553129.jpg)
相关文章推荐
- 比较C#中几种常见的复制字节数组方法的效率
- C# 常见的字节数组 byte[] 复制方法
- C# 常见的字节数组 byte[] 复制方法
- C# 常见的字节数组 byte[] 复制方法
- [C#]几种字符串反转方法效率比较
- java中几种复制数组的方法比较
- C# 中数组的复制的几种方法
- C#复制数组的两种方式,以及效率比较
- C#复制数组的两种方式,以及效率比较
- 关于C#中字节数组复制的五种方法
- [C#]几种字符串反转方法效率比较
- C#访问BitMap几种方法效率比较
- C#清除数组中数据的几种方法及性能比较
- C#抽象工厂模式的几种实现方法及比较【精】
- C#抽象工厂模式的几种实现方法及比较
- C#抽象工厂模式的几种实现方法及比较
- C#中数组复制的四种方法
- 线程同步的几种方法效率比较
- C#抽象工厂模式的几种实现方法及比较
- Asp.net 几种分页方法效率比较