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

前端 未结 7 1978
独厮守ぢ
独厮守ぢ 2020-12-02 13:01

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

相关标签:
7条回答
  • 2020-12-02 13:41

    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.

    0 讨论(0)
提交回复
热议问题