Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Java's System.arraycopy() efficient for small arrays?

Is Java's System.arraycopy() efficient for small arrays, or does the fact that it's a native method make it likely to be substantially less efficient than a simple loop and a function call?

Do native methods incur additional performance overhead for crossing some kind of Java-system bridge?

like image 603
Gravity Avatar asked Dec 15 '11 21:12

Gravity


People also ask

Is system Arraycopy faster than for loop?

arraycopy() is a native call, which is most certainly faster.

Does System Arraycopy create a new array?

arraycopy() simply copies values from the source array to the destination, Arrays. copyOf() also creates new array. If necessary, it will truncate or pad the content.

Does Arraycopy work for 2D arrays?

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. To use this method, we need to provide the following parameters: src : source array that you need to copy.

What is the use of system Arraycopy?

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 .


1 Answers

Expanding a little on what Sid has written, it's very likely that System.arraycopy is just a JIT intrinsic; meaning that when code calls System.arraycopy, it will most probably be calling a JIT-specific implementation (once the JIT tags System.arraycopy as being "hot") that is not executed through the JNI interface, so it doesn't incur the normal overhead of native methods.

In general, executing native methods does have some overhead (going through the JNI interface, also some internal JVM operations cannot happen when native methods are being executed). But it's not because a method is marked as "native" that you're actually executing it using JNI. The JIT can do some crazy things.

Easiest way to check is, as has been suggested, writing a small benchmark, being careful with the normal caveats of Java microbenchmarks (warm up the code first, avoid code with no side-effects since the JIT just optimizes it as a no-op, etc).

like image 169
vanza Avatar answered Oct 15 '22 02:10

vanza