Joe
Joe

Reputation: 16841

Is it correct to use Array.CopyTo to copy elements or should a for-loop always be used?

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?

Upvotes: 2

Views: 1832

Answers (3)

Dave White
Dave White

Reputation: 3461

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)

Upvotes: 1

Tim C
Tim C

Reputation: 1934

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.

Upvotes: 0

Mikael Svenson
Mikael Svenson

Reputation: 39695

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.

Upvotes: 3

Related Questions