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
Instead of relying on speculation and possibly outdated information, I ran some benchmarks using caliper. In fact, Caliper comes with some examples, including a CopyArrayBenchmark that measures exactly this question! All you have to do is run
mvn exec:java -Dexec.mainClass=com.google.caliper.runner.CaliperMain -Dexec.args=examples.CopyArrayBenchmark
My results are based on Oracle's Java HotSpot(TM) 64-Bit Server VM, 1.8.0_31-b13, running on a mid-2010 MacBook Pro (macOS 10.11.6 with an Intel Arrandale i7, 8 GiB RAM). I don't believe that it's useful to post the raw timing data. Rather, I'll summarize the conclusions with the supporting visualizations.
In summary:
for
loop to copy each element into a newly instantiated array is never advantageous, even for arrays as short as 5 elements.Arrays.copyOf(array, array.length)
and array.clone()
, but not quite consistently so. (See the case for 50000 int
s.) Because of that, and the verbosity of the call, I would recommend System.arraycopy()
if you need fine control over which elements get copied where.Here are the timing plots: