Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is more efficient: System.arraycopy or Arrays.copyOf?

The toArray method in ArrayList, Bloch uses both System.arraycopy and Arrays.copyOf to copy an array.

public <T> T[] toArray(T[] a) {     if (a.length < size)         // Make a new array of a's runtime type, but my contents:         return (T[]) Arrays.copyOf(elementData, size, a.getClass());     System.arraycopy(elementData, 0, a, 0, size);     if (a.length > size)         a[size] = null;     return a; } 

How can I compare these two copy methods and when should I use which?

like image 982
Sawyer Avatar asked Apr 07 '10 03:04

Sawyer


People also ask

Is Arraycopy fast?

arraycopy() wins, for smaller than 10, manual for loop is better... Now I'm really confused. 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.

Is system Arraycopy deep copy?

System. arraycopy does shallow copy, which means it copies Object references when applied to non primitive arrays. Therefore after System.

Does Arraycopy work for 2D arrays?

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.


1 Answers

The difference is that Arrays.copyOf does not only copy elements, it also creates a new array. System.arraycopy copies into an existing array.

Here is the source for Arrays.copyOf, as you can see it uses System.arraycopy internally to fill up the new array:

public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {     T[] copy = ((Object)newType == (Object)Object[].class)         ? (T[]) new Object[newLength]         : (T[]) Array.newInstance(newType.getComponentType(), newLength);     System.arraycopy(original, 0, copy, 0,                      Math.min(original.length, newLength));     return copy; } 
like image 120
Thilo Avatar answered Oct 17 '22 23:10

Thilo