开发者

What is the difference between Array.Copy and Array.CopyTo?

开发者 https://www.devze.com 2022-12-09 06:53 出处:网络
Is there any d开发者_运维百科ifference between Array.Copy and CopyTo? Are they just overloaded?Same functionality, different calling conventions. Copy is a static method, while CopyTo isn\'t.

Is there any d开发者_运维百科ifference between Array.Copy and CopyTo? Are they just overloaded?


Same functionality, different calling conventions. Copy is a static method, while CopyTo isn't.

Array.Copy(arraySrc, arrayDest, arraySrc.length);
arraySrc.CopyTo(arrayDest, startingIndex);


Look at it carefully. Copy is a static method whereas CopyTo is an instance method.


But they are not only convention-wise different; there is a key functional difference.

Here is an excerpt from MSDN:

This method (Array.CopyTo) supports the System.Collections.ICollection interface. If implementing System.Collections.ICollection is not explicitly required, use Copy to avoid an extra indirection.


Comparing
https://msdn.microsoft.com/en-us/library/k4yx47a1.aspx and
https://msdn.microsoft.com/en-us/library/06x742cw.aspx,
We will see that:

Array.CopyTo

  • able to copy multidimensional arrays.
  • easier to specify range to be copied.
  • static method.

CopyTo

  • have better performance. (as husayt answered)
  • instance method.

And there are something I am not sure that, the remarks of Array.CopyTo said:

This method is equivalent to the standard C/C++ function memmove, not memcpy.

Which CopyTo do not have such description.
It is true that it is not easy to copy part of an array to it self using CopyTo without parameters to control range. Still, you could use ArraySegment or array.Skip(offset).Take(length) to achieve it.
And in my test, there is no problem to do so.


Functionally, I don't know if there is anything different between the two other than the CopyTo method will copy all elements of the array and Copy will allow you to specify a range of elements to copy

0

精彩评论

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