使用单个值填充数组的最快方法

cha*_*adb 14 c# memory algorithm optimization performance

我想用我所拥有的单个值填充2D数组,但是,我想尽可能以最快的方式完成2D数组的长度总计200k +并且随着时间的推移将有超过200个这样的数组.我查看了Buffer.BlockCopy和Array.Copy,但是,它们都将数组作为源/目标,其中我唯一的数组是目标,源是单个值.

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

Gra*_*x32 9

我发现的最快的方法是使用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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我在http://coding.grax.com/2011/11/initialize-array-to-value-in-c-very.htmlhttp://coding.grax.com/2014/04/better上写了这篇博文.-阵列-填充- function.html

  • 我需要填充[,]数组,所以我复制了你的`Fill`扩展并将签名更改为`public static void Fill <T>(this T [,] destinationArray,T [,] value)`并将其称为所以:`myLargeArray.Fill(new [,] {{double.NaN},{double.NaN}});`它工作得很好.谢谢! (2认同)