This test
for (;;) {
int[] a = new int[10];
System.gc();
long t0 = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
// int[] b = a.clone();
int[] b = Arrays.copyOf(a, a.length);
}
System.out.println(System.currentTimeMillis() - t0);
}
shows ~50ms for Arrays.copyOf and ~160 ms for clone. Clone is a special native method for making copies, why is it so slow?
I ran the test on my HotSpot Client JVM 1.7.0_11-b21. Note that when the array increases in size, the difference between clone and copyOf disappears.
I’ve found a good article explaining why clone is slow here http://www.javaspecialists.eu/archive/Issue124.html. To put it shortly, it’s because int[].clone simply uses Object.clone and this method makes two checks before copying the array:
1.Check whether instance is normal object or array.
2.Check whether array is of primitives or objects.
I added these checks to the Arrrays.copyOf test
and the test showed no difference between clone and Arrays.copyOf. Had it been a specialized version for arrays clone would have been fast.