Is there any reason to prefer System.arraycopy() over clone()?
clone()
makes a distinct copy of the first array with its own reference.System.arraycopy()
uses JNI (Java Native Interface) to copyan array (or parts of it), so it isblazingly fast, as you can confirmhere;clone()
creates a new array with the same characteristics as the old array, i.e., same size, same type, and same contents. Refer to here for some examples ofclone
in action;manual copying
is, well, manual copying. There isn't much to say about this method, except that many people have found it to be the most performant.arraynew = arrayold
doesn't copy the array; it just pointsarraynew
to the memory address ofarrayold
or, in other words, you are simply assigning a reference to the old array.
I happened to look at this question when I was pondering on the same doubt. I feel that the arraycopy()
is a method to be used when the array is predefined (i.e. memory is already allocated). Thus, the overhead associated with memory allocation is not repeated.
For example, imagine a case when you have defined a large array which is updated periodically. Then using clone()
will recreate a array of required size every time the array is copied. However, arraycopy()
uses the pre-allocated memory space.
Thus arraycopy()
is more efficient in certain scenarios compared to clone()
. On the other hand clone()
results in a compact code.