Quantcast
Viewing all articles
Browse latest Browse all 11

Answer by Stephen C for What is more efficient: System.arraycopy or Arrays.copyOf?

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 base type of 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 that 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 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-code loop that there is no difference.


Viewing all articles
Browse latest Browse all 11

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>