Java – why is cloning arrays so slow?
•
Java
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); }
Display arrays Copyof is about 50ms and clone display is about 160ms Cloning is a special native method to make copies. Why is it so slow?
I'm in hotspot client JVM 1.7 0_ Run the test on 11-b21 Note that as the array size increases, the difference between clone and copyof disappears
Solution
I run your code on your system: there is little difference between them Both clocks are about 30 milliseconds My test was conducted on openjdk 7
To confirm, I also run it through caliper and use a larger array to emphasize the actual replication performance:
public class Performance extends SimpleBenchmark { final int[] source = new int[1000]; public int timeClone(int reps) { int sum = 0; for (int i = reps; i > 0; i--) sum += source.clone().length; return sum; } public int timeCopyOf(int reps) { int sum = 0; for (int i = reps; i > 0; i--) sum += Arrays.copyOf(source,source.length).length; return sum; } public static void main(String... args) { Runner.main(Performance.class,args); } }
result:
0% Scenario{vm=java,trial=0,benchmark=Clone} 2141.70 ns; σ=5416.80 ns @ 10 trials 50% Scenario{vm=java,benchmark=CopyOf} 2168.38 ns; σ=1545.85 ns @ 10 trials benchmark us linear runtime Clone 2.14 ============================= CopyOf 2.17 ============================== vm: java trial: 0
Upon request, the array size here is 10:
0% Scenario{vm=java,benchmark=Clone} 30.07 ns; σ=2.12 ns @ 10 trials 50% Scenario{vm=java,benchmark=CopyOf} 29.34 ns; σ=161.38 ns @ 10 trials benchmark ns linear runtime Clone 30.1 ============================== CopyOf 29.3 =============================
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码