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?

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;
}

System.arraycopy() vs. Arrays.copyOf() in Java, The toArray method in ArrayList, Bloch uses both System.arraycopy and Arrays.​copyOf to copy an array. The method Arrays.copyOf () internally makes use of the System.arraycopy () method. Though it is not as efficient as arraycopy, it can be used to copy full or partial array just like the arraycopy method. ‘copyOf ()’ method is a part of the java.util package and belongs to the “Arrays” class. The prototype of this method is as follows:

While System.arraycopy is implemented natively, and is therefore could be1 faster than a Java loop, it is not always as fast as you might expect. Consider this example:

Object[] foo = new Object[]{...};
String[] bar = new String[foo.length];

System.arraycopy(foo, 0, bar, 0, bar.length);

In this case, the foo and bar arrays have different base types, so the implementation of arraycopy has to check the type of every reference copied to make sure that it is actually a reference to a String instance. That is significantly slower than a simple C-style memcopy of the array contents.

The other point is that Arrays.copyOf uses System.arraycopy under the hood. Therefore System.arraycopy is on the face of it should not be slower2 than Arrays.copyOf. But you can see (from the code quoted above) that Arrays.copyOf will in some cases use reflection to create the new array. So the performance comparison is not straightforward.

There are a couple of flaws in this analysis.

  1. We are looking at the implementation code from a specific version of Java. These methods may change, invalidating previous assumptions about efficiency.

  2. We are ignoring the possibility that the JIT compiler could do some clever special case optimization for these methods. And it apparently this does happen with Arrays.copyOf; see Why is Arrays.copyOf 2 times faster than System.arraycopy for small arrays?. This method is "intrinsic" in current-generation Java implementations, which means that the JIT compiler will ignore what is in the Java source code!

But either way, the difference between the two versions is O(1) (i.e. independent of array size) and relatively small. Therefore, my advice would be to use the version that makes your code easiest to read, and only worry about which one is faster if profiling tells you that it matters.


1 - It could be faster, but it is also possible that the JIT compiler does such a good job of optimizing a hand-coded loop that there is no difference.

What is more efficient: System.arraycopy or Arrays.copyOf?, Array copy may seem like a trivial task, but it may cause unexpected results and program behaviors if not done carefully. 2. The System Class. AFAIK, System.arrayCopy is the most efficient and best way to copy your arrays. I am not aware of any situations where the alternate way of implementing your own loops would be much more efficient for direct copies.

If you want an exact copy of an array (say, if you want to do a defensive copy), the most effective way of copying an array is probably using the array object's clone() method:

class C {
    private int[] arr;
    public C(int[] values){
        this.arr = values.clone();
    }
}

I haven't bothered to test the performance of it, but it stands a good chance to be pretty fast since it's all native (allocation and copying in call), and cloning is kind of a special JVM blessed way of copying objects (and it's mostly evil for other purposes) and is likely to be able to take some "shortcuts".

Personally, I'd still use clone if it was slower than any other way of copying, because it's easier to read and nigh-impossible to screw up when writing. System.arrayCopy, on the other hand...

How to Copy an Array in Java, Java allows you to copy arrays using either direct copy method provided by Java's System class has a method called “ArrayCOpy” that allows you to Though it is not as efficient as arraycopy, it can be used to copy full or partial This means if the length of the copied array is more than the original array,  Arrays.copyOf can only be used to either copy the entire array or a prefix of the array (i.e. all the elements from the first element until some index). You have to first calculate the required length of the output array, instantiate the output array and then iterate over the elements of the input array and copy the relevant elements one by one

System.arrayCopy is much faster. It's in system because it uses a direct memory copy outside of Java land. Use it when possible.

Java Copy Array: How To Copy / Clone An Array In Java, Given an array, we need to copy its elements in a different array. System.​arraycopy() is faster than clone() as it uses Java Native Interface (Source  Java examples to copy an array to another array object using array clone, System.arrayCopy() and Arrays.copyOf() methods. Note that all given below approaches create shallow copy of array. To create deep copies of array , follow provided link.

Have you looked at the Sun's implementation of Arrays.copyOf()?

 public static int[] copyOf(int[] original, int newLength) {
    int[] copy = new int[newLength];
    System.arraycopy(original, 0, copy, 0,
                     Math.min(original.length, newLength));
    return copy;
}

As can be seen, it uses System.arraycopy() internally, so the performance would be the same.

Array Copy in Java, What is more efficient: System.arraycopy or Arrays.copyOf?, arraycopy() method copies a source array from a specific beginning position to the destination array  System.arrayCopy is implemented natively, and hence will be faster than any Java code. I recommend you to use it. The toArray method in ArrayList, Bloch uses both System.arraycopy and Arrays.copyOf to copy an array.

Efficient System.arraycopy on multidimensional arrays, Java Copy Arrays (Using System arraycopy(), Looping construct and , An array is not a primitive The most efficient copying data between arrays is provided by  An array is an aggregate data structure that is designed to store a group of objects of the same or different types. Arrays can hold primitives as well as references. The array is the most efficient data structure for storing and accessing a sequence of objects.

Efficient System.arraycopy on multidimensional arrays, To learn more about the method, visit Java copyOfRange. 5. Copying 2d Arrays Using Loop. Similar to the single-dimensional array, we can also copy the 2-  System.arraycopy () provides convenient and very efficient way to copy arrays in Java. We can make use of this method to copy elements of given arrays into a newly allocated empty array.

Java Copy Arrays (Using System arraycopy(), Looping construct and , one might expect a.clone() to be equally fast or perhaps even faster than the equivalent Arrays.copyOf(a, 1) or Object[] x = new Object[1]; System.arraycopy(a,​  Arrays copyOf() in Java with examples java.util.Arrays.copyOf() method is in java.util.Arrays class. It copies the specified array, truncating or padding with false (if necessary) so the copy has the specified length.

Comments
  • What is "Bloch"? Why is the code snippet relevant?
  • @Ciro Bloch is the guy who wrote the ArrayList implementation.
  • See also: stackoverflow.com/q/44487304/14955
  • Its obvious....Arrays.copyOf should create a new instance of array as we are not passing one to it; while we pass a destination to System.arraycopy. Regarding speed, again obviously System.arraycopy should win as it is a native method and ultimately Arrays.copyOf also calls this method for copying an array.
  • The Java source doesn't matter since the intrinsic was created.
  • also System.arraycopy has more detailed parameters, you can specify start index for both arrays.
  • public class TestClass { public static void main(String[] args) { byte a[] = { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74 }; System.arraycopy(a, 0, a, 1, a.length - 1); System.out.println(new String(a)); } }
  • code above prints AABCDEFGHI that means it's creating a new array.
  • +1 for pointing out the type checking that has to take place sometimes.
  • @StephenC, Regarding your first paragraph, are there cases where System.arrayCopy could actually be slower?
  • @Pacerier - I'm not aware of any. But it is not impossible.
  • A little late on this response but keeping in mind that System.arrayCopy is referenced by Arrays.copyOf (As is mentioned in the accepted answer) I would have to aruge that it is impossible for System.arrayCopy to be slower. This provided, of course, that it is not a custom implementation of JVM with a custom implementation of the methods.