Use Array.Copy to copy arrays quickly in C#

It's easy enough to copy an array by using a for loop, but for most arrays you can get even better performance by using the Array class's Copy method. This takes as parameters the arrays between which to copy. A third parameter tells how many entries to copy. Optional parameters let you copy from one part of the source array to another part of the destination array.

The following code compares the times needed to copy an array by using a for loop and by using Array.Copy.

// Run the trials.
private void btnGo_Click(object sender, EventArgs e)
{
lblForLoop.Text = "";
lblArrayCopy.Text = "";
Cursor = Cursors.WaitCursor;
Application.DoEvents();

int num_items = int.Parse(txtNumItems.Text);
int num_trials = int.Parse(txtNumTrials.Text);

int[] array1 = new int[num_items];
int[] array2 = new int[num_items];

// Initialize the first array.
for (int i = 0; i < num_items; i++)
{
array1[i] = i;
}
DateTime start_time, stop_time;
TimeSpan elapsed;

// Use a for loop.
start_time = DateTime.Now;
for (int trial = 0; trial < num_trials; trial++)
{
for (int i = 0; i < num_items; i++)
{
array2[i] = array1[i];
}
}
stop_time = DateTime.Now;
elapsed = stop_time - start_time;
lblForLoop.Text = elapsed.TotalSeconds.ToString("0.00") + " seconds";
Application.DoEvents();

// Use Array.Copy.
start_time = DateTime.Now;
for (int trial = 0; trial < num_trials; trial++)
{
Array.Copy(array1, array2, array1.Length);
}
stop_time = DateTime.Now;
elapsed = stop_time - start_time;
lblArrayCopy.Text = elapsed.TotalSeconds.ToString("0.00") + " seconds";

Cursor = Cursors.Default;
}

The code gets the number of items it should copy in each array and the number of trials it should perform. Then for each trial, the code uses a for loop to copy the array's values and displays the elapsed time. It then copies the values using Array.Copy.

If you look closely at the picture, you'll see that Array.Copy is much faster, in this example taking about 1/8th as long as a for loop.

Note that the total time is very extremely small (only about 8 nanoseconds per item using a for loop). Also note that a for loop may be faster for very small arrays.

A bigger benefit to Array.Copy than the speed advantage is the fact that the code is more concise and easier to read, at least when you get used to it.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.