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?
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 .
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.
System. arraycopy does shallow copy, which means it copies Object references when applied to non primitive arrays. Therefore after System.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With