c# – 用单个值填充数组的最快方法

参见英文答案 > What is the equivalent of memset in C#?                                    11
我想填充一个具有单个值的二维数组,但是,我想以最快的方式做到,2D数组的长度总共将达到200k,并且随着时间的推移,这些数组将超过200个.我已经研究了BufferBlockCopy和Array.Copy,但是它们都将数组作为源/目的地,其中唯一的数组是目的地,源是一个单一的值.

填充数组的最快方法是以源为单值而不是数组?

我发现最快的方法是使用Array.Copy,每次通过循环复制大小加倍.无论您是使用单个值还是数组数组填充数组,速度基本相同.

在我的20,000,000个数组项目的测试中,该函数是for循环的两倍.

using System;

namespace Extensions
{
    public static class ArrayExtensions
    {
        public static void Fill<T>(this T[] destinationArray, params T[] value)
        {
            if (destinationArray == null)
            {
                throw new ArgumentNullException("destinationArray");
            }

            if (value.Length >= destinationArray.Length)
            {
                throw new ArgumentException("Length of value array must be less than length of destination");
            }

            // set the initial array value
            Array.Copy(value, destinationArray, value.Length);

            int arrayToFillHalfLength = destinationArray.Length / 2;
            int copyLength;

            for(copyLength = value.Length; copyLength < arrayToFillHalfLength; copyLength <<= 1)
            {
                Array.Copy(destinationArray, 0, destinationArray, copyLength, copyLength);
            }

            Array.Copy(destinationArray, 0, destinationArray, copyLength, destinationArray.Length - copyLength);
        }
    }
}

我在http://coding.grax.com/2011/11/initialize-array-to-value-in-c-very.htmlhttp://coding.grax.com/2014/04/better-array-fill-function.html发表了这个消息

翻译自:https://stackoverflow.com/questions/5943850/fastest-way-to-fill-an-array-with-a-single-value

转载注明原文:c# – 用单个值填充数组的最快方法