Reputation: 16841
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
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
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
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