最快以填补一个值数组的方式 [英] Fastest way to fill an array with a single value

查看:113
本文介绍了最快以填补一个值数组的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想填补一个二维数组相同的值,我,但我想这样做最快的方式有二维数组的长度将是一个总的200K +,并随着时间的推移,将有超过200这些阵列。不过,我已经调查Buffer.BlockCopy和Array.Copy,他们都采取数组作为源/目的,其中唯一阵列我是目的,源是一个单一的值。

I would like to fill a 2D array with a single value that I have, however, I would like to do it the quickest way possible has the 2D array's length will be a total of 200k+ and over time there will be over 200 of these arrays. I have looked into Buffer.BlockCopy and Array.Copy, however, they both take in arrays as the source/destination, where the only array I have is the destination, with the source being a single value.

什么是填写一个数组与源是一个单一的值,而不是最快的方式数组?

What is the fastest way to fill in an array with the source being a single value and not an array?

推荐答案

的最快方法我发现使用Array.Copy与复印尺寸每次循环的时间延长一倍。的速度基本上是一样的,你是否填充阵列与单个值或值的阵列

The fastest method I have found uses Array.Copy with the copy size doubling each time through the loop. The speed is basically the same whether you fill the array with a single value or an array of values.

在我的测试中有2000万阵列项目,该功能是快两倍,一个for循环。

In my test with 20,000,000 array items, this function is twice as fast as a for loop.

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);
        }
    }
}

我的博客上讲述这个在<一个href="http://coding.grax.com/2011/11/initialize-array-to-value-in-c-very.html">http://coding.grax.com/2011/11/initialize-array-to-value-in-c-very.html和<一href="http://coding.grax.com/2014/04/better-array-fill-function.html">http://coding.grax.com/2014/04/better-array-fill-function.html

这篇关于最快以填补一个值数组的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆