Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is System.arraycopy native in Java?

I was surprised to see in the Java source that System.arraycopy is a native method.

Of course the reason is because it's faster. But what native tricks is the code able to employ that make it faster?

Why not just loop over the original array and copy each pointer to the new array - surely this isn't that slow and cumbersome?

like image 699
James B Avatar asked May 05 '10 10:05

James B


People also ask

What does system Arraycopy do in Java?

arraycopy. Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. A subsequence of array components are copied from the source array referenced by src to the destination array referenced by dest .

Why is Arraycopy in system?

System. arraycopy() copies the array contents from the source array, beginning at the specified position, to the designated position in the destination array. Additionally, before copying, the JVM checks that both source and destination types are the same.

Is system Arraycopy deep copy?

System. arraycopy does shallow copy, which means it copies Object references when applied to non primitive arrays. Therefore after System.

Does Arraycopy work for 2D arrays?

Using arraycopy() Method to Copy 2D Array in Java Likewise, we can copy 2D arrays using the arraycopy() method. We can copy elements of any 2D array without iterating all the array elements with this method.


1 Answers

In native code, it can be done with a single memcpy / memmove, as opposed to n distinct copy operations. The difference in performance is substantial.

like image 50
Péter Török Avatar answered Oct 01 '22 01:10

Péter Török