devlights
4/2/2014 - 7:16 AM

プリミティブ型の配列操作ではArray.CopyよりもBuffer.BlockCopyの方が速い

プリミティブ型の配列操作ではArray.CopyよりもBuffer.BlockCopyの方が速い

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace BufferSample
{
    class Program
    {
        static void Main(string[] args)
        {
            const int sizeOfInt = sizeof(int);

            var intArray = Enumerable.Range(1, (1024 * 256 * 256)).ToArray();
            var result1 = new int[intArray.Length];
            var result2 = new int[intArray.Length];

            var watch = Stopwatch.StartNew();
            Array.Copy(intArray, result1, intArray.Length);
            watch.Stop();

            Console.WriteLine(
                "Array.Copy={0}ms (length={1})", 
                watch.ElapsedMilliseconds, 
                intArray.Length);

            watch.Reset();
            watch.Start();

            Buffer.BlockCopy(
                intArray,
                (0 * sizeOfInt), 
                result2, 
                (0 * sizeOfInt), 
                (intArray.Length * sizeOfInt));
            
            watch.Stop();

            Console.WriteLine(
                "Buffer.BlockCopy={0}ms (length={1})", 
                watch.ElapsedMilliseconds, 
                intArray.Length);
        }
    }
}