System.arraycopy浅拷贝性能为何随数组长度差异巨大?
System.arraycopy不同拷贝长度的性能差异分析
我原本认为System.arraycopy作为浅拷贝实现,无论拷贝元素数量多少,开销都很低,于是编写了以下JMH测试代码:
private static int[] randomInts = new int[800]; @Setup public void setup() { Random rand = new Random(); for (int i = 0; i < 800; i++) { randomInts[i] = rand.nextInt(10000) + 1; } } // Copy first 20 elements from randomInts @Benchmark public int[] testFirst20() { final int[] toArray = new int[20]; System.arraycopy(randomInts, 0, toArray, 0, 20); return toArray; } // Copy the whole randomInts @Benchmark public int[] testFull() { final int[] toArray = new int[800]; System.arraycopy(randomInts, 0, toArray, 0, 800); return toArray; }
第一次测试结果如下:
Benchmark Mode Cnt Score Error Units BenchAddToArray.testFirst20 thrpt 5 116484.035 ± 9793.886 ops/ms BenchAddToArray.testFull thrpt 5 3348.843 ± 429.225 ops/ms
从结果能看出,即使是浅拷贝也需要关注性能表现。我知道完整拷贝比小范围拷贝开销更高,但没想到差异如此显著。请问System.arraycopy的哪一部分导致了不同长度数组拷贝的性能差异?
感谢@Sweeper的建议,我调整了测试版本,将数组初始化移至@Setup中,让基准测试仅针对arrayCopy逻辑,得到以下结果:
Benchmark Mode Cnt Score Error Units BenchAddToArray.testFirst20 thrpt 5 30061.031 ± 4521.763 ops/ms BenchAddToArray.testFull thrpt 5 2753.594 ± 117.719 ops/ms
可见数组初始化是造成性能差异的主要因素之一。
内容的提问来源于stack exchange,提问作者waynewingorc
相关产品推荐
相关产品推荐

