1. 程式人生 > >比較C#中幾種常見的複製位元組陣列方法的效率

比較C#中幾種常見的複製位元組陣列方法的效率

        在日常程式設計過程中,我們可能經常需要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);
        }
    }
}

       執行結果如下:


       希望以上測試對您會有所幫助。

版權所有,轉載請註明。