BLOG.CSHARPHELPER.COM: Use Array.Copy to copy arrays quickly in C#
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.
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.
Comments