Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Array.Copy safe when the source and destination are the same array?

Tags:

c#

I'm currently using Array.Copy to shift an array as such:

Array.Copy(array, 0, array, 1, array.Length - 1); 

It's noticeable faster than using a loop. I know that similar functions in other languages (eg. memcpy) are undefined or sometimes break when the compiler gets too aggressive. Is it reasonable to consider this safe in .NET?

like image 261
Zong Avatar asked Jun 22 '12 03:06

Zong


People also ask

Can arrays be copied?

The array can be copied by iterating over an array, and one by one assigning elements. We can avoid iteration over elements using clone() or System. arraycopy()

How does array copy work?

Copy(Array, Array, Int64) Copies a range of elements from an Array starting at the first element and pastes them into another Array starting at the first element. The length is specified as a 64-bit integer.

Which of the following can be used to copy data from one array to another?

There are multiple ways to copy elements from one array in Java, like you can manually copy elements by using a loop, create a clone of the array, use Arrays. copyOf() method or System. arrayCopy() to start copying elements from one array to another in Java.


1 Answers

Yes, it is safe. It is documented how the method should behave in this case:

If sourceArray and destinationArray overlap, this method behaves as if the original values of sourceArray were preserved in a temporary location before destinationArray is overwritten.

like image 82
Mark Byers Avatar answered Sep 28 '22 02:09

Mark Byers