Fast array fill function (revisited)

Update:  A reader ( +Michael Hsu ) posted a faster improved version at and I blogged about it at

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. }
  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.     }
  14.     // set the initial array value
  15.     Array.Copy(fillValue, arrayToFill, fillValue.Length);
  17.     int arrayToFillHalfLength = arrayToFill.Length / 2;
  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.         }
  27.         Array.Copy(arrayToFill, 0, arrayToFill, i, copyLength);
  28.     }
  29. }
Improve Your Life
Improve Your Team
Improve Your Code
Software Projects

David Walker

David Walker is a Secure Software Consultant, a Certified Secure Software Lifecycle Professional (CSSLP), and a Professional Scrum Master. He believes in secure and reliable software and productive happy teams. He lives in Orlando with his lovely wife Lynn and his 2 dogs.