views:

61

answers:

3

It's easier to write

intArray1.CopyTo( intArray2, 0 )

than the for-loop equivalent, but System.Array does not provide any generic Copy/CopyTo methods.

Is it better to write the for-loop? Or is using Copy/CopyTo compiled or JIT'd efficiently enough?

+2  A: 

Array.Copy/CopyTo will perform faster than a manual loop in most cases as it can do direct memory copying.

If you don't have huge arrays or speed is not an issue, use whatever would look best in your code where you need to copy the items.

Mikael Svenson
Agreed, since the static Array.Copy and Array.CopyTo methods will do exactly as the question asked.
Eric Falsken
Do you have any proof of this? I'm not arguing against you, but I'd like to see some proof to support your claim. It looks like the Array.Copy method is implemented internally in the CLR.
John Leidegren
@John, I actually made the assumption since it's internally in the CLR. I did some benchmarking on int arrays, and .CopyTo is faster for arrays smaller than ~700.000 items (a bit more if you run it unchecked) More items and a for loop is faster on int arrays. Weird indeed. Also see this post for comparison: http://waldev.blogspot.com/2008/05/efficiently-copying-items-from-one.html
Mikael Svenson
Those performance numbers are always misleading, I did some comparsion on array lookup of different arrays with the Microsoft CLR and Mono and the numbers there were also misleading. http://stackoverflow.com/questions/597720/what-is-differences-between-multidimensional-array-and-array-of-arrays-in-c/597790#597790 sufficent to say, there's no logical reasoning which can be applied here, you'll have to run that profiler and see for yourself.
John Leidegren
A: 

I say if you know that you want to copy the entirety of the first array to the second array without changing the values or doing any specific processing on the copy, then use Array.CopyTo.

There are some limitations to this. The array must only have a single dimension as I remember it. Also if the arrays are quite large you might have some speed related issues with the copyto, but I would imagine that would only come into play with very large arrays. So, I would try it and test it, but your mileage may vary.

Tim C
+1  A: 

If you are copying an array of primitive types as your sample would imply, you can us the memory copy technique yourself using the Buffer classes BlockCopy method.

    int[] CopyArray(int[] A, int index)
    {
        const int INT_SIZE = 4;
        int length = A.Length - index;
        int[] B = new int[A.Length - index];
        Buffer.BlockCopy(A, index * INT_SIZE, B,
                         0 * INT_SIZE, length * INT_SIZE); 
        return B;
    }

This method is the most efficient manner in which to copy an array of primitives. (It only works with primitives)

Dave White