开发者

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?


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.


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜