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 s
This is a valid concern. For example, in java.nio.DirectByteBuffer.put(byte[])
, the author tries to avoid a JNI copy for small number of elements
// These numbers represent the point at which we have empirically
// determined that the average cost of a JNI call exceeds the expense
// of an element by element copy. These numbers may change over time.
static final int JNI_COPY_TO_ARRAY_THRESHOLD = 6;
static final int JNI_COPY_FROM_ARRAY_THRESHOLD = 6;
For System.arraycopy()
, we can examine how JDK uses it. For example, in ArrayList
, System.arraycopy()
is always used, never "element by element copy", regardless of length (even if it's 0). Since ArrayList
is very performance conscious, we can derive that System.arraycopy()
is the most effecient way of array copying regardless of length.