Fast array fill function (revisited)

Update:  A reader ( +Michael Hsu ) posted a faster improved version at https://github.com/mykohsu/Extensions/blob/master/ArrayExtensions.cs and I blogged about it at http://coding.grax.com/2014/04/better-array-fill-function.html

Looking back at my first blog post, I decided to revisit it.

The function is succinct, blazingly fast, and I am quite proud of it.

Here’s what it does.  Given an array of any type (byte, int, string), fill the array with a single value or a repeating pattern of values.

Usage is very simple.

Define an array, for example:

byte[] myByteArray = new byte[12345];


Call ArrayFill with the array variable and a value to fill the array with.

ArrayFill(myByteArray, (byte)3);


At this point the array is completely filled with a byte of 3.

Call it with a second array to fill your array with a repeating pattern.

ArrayFill(myByteArray, new byte[] { 3, 4, 1, 9 });


At this point the array is filled with a repeating pattern of bytes.  3,4,1,9,3,4,1,9,3,4,1,9, etc


Code Snippet 
  1. public static void ArrayFill<T>(T[] arrayToFill, T fillValue)
  2. {
  3.     // if called with a single value, wrap the value in an array and call the main function
  4.     ArrayFill(arrayToFill, new T[] { fillValue });
  5. }
  6.  
  7. public static void ArrayFill<T>(T[] arrayToFill, T[] fillValue)
  8. {
  9.     if (fillValue.Length >= arrayToFill.Length)
  10.     {
  11.         throw new ArgumentException("fillValue array length must be smaller than length of arrayToFill");
  12.     }
  13.  
  14.     // set the initial array value
  15.     Array.Copy(fillValue, arrayToFill, fillValue.Length);
  16.  
  17.     int arrayToFillHalfLength = arrayToFill.Length / 2;
  18.  
  19.     for (int i = fillValue.Length; i < arrayToFill.Length; i *= 2)
  20.     {
  21.         int copyLength = i;
  22.         if (i > arrayToFillHalfLength)
  23.         {
  24.             copyLength = arrayToFill.Length - i;
  25.         }
  26.  
  27.         Array.Copy(arrayToFill, 0, arrayToFill, i, copyLength);
  28.     }
  29. }
Home
Improve Your Life
Improve Your Team
Improve Your Code
Opinion
Software Projects
Foo Network