Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to fill an array with a single value [duplicate]

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?

like image 663
chadb Avatar asked May 10 '11 00:05

chadb


People also ask

How do you initialize an entire array with value 1?

Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays. int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index.

How do you fill an array?

Using the fill() method The fill() method, fills the elements of an array with a static value from the specified start position to the specified end position. If no start or end positions are specified, the whole array is filled. One thing to keep in mind is that this method modifies the original/given array.


1 Answers

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.

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

I blogged about this at https://secureapplicationlifestyle.com/2011/11/initialize-array-to-value-in-c-very.html and https://secureapplicationlifestyle.com/2014/04/better-array-fill-function.html

like image 51
Grax32 Avatar answered Sep 30 '22 15:09

Grax32