【发布时间】:2014-08-10 11:05:35
【问题描述】:
我想知道为什么一次分配一个 2D int 数组 (new int[50][2]) 性能比单独分配差,即先执行new int[50][],然后一个接一个地执行new int[2]。这是一个非专业的基准代码:
public class AllocationSpeed {
private static final int ITERATION_COUNT = 1000000;
public static void main(String[] args) {
new AllocationSpeed().run();
}
private void run() {
measureSeparateAllocation();
measureAllocationAtOnce();
}
private void measureAllocationAtOnce() {
Stopwatch stopwatch = Stopwatch.createStarted();
for (int i = 0; i < ITERATION_COUNT; i++) {
allocateAtOnce();
}
stopwatch.stop();
System.out.println("Allocate at once: " + stopwatch);
}
private int allocateAtOnce() {
int[][] array = new int[50][2];
return array[10][1];
}
private void measureSeparateAllocation() {
Stopwatch stopwatch = Stopwatch.createStarted();
for (int i = 0; i < ITERATION_COUNT; i++) {
allocateSeparately();
}
stopwatch.stop();
System.out.println("Separate allocation: " + stopwatch);
}
private int allocateSeparately() {
int[][] array = new int[50][];
for (int i = 0; i < array.length; i++) {
array[i] = new int[2];
}
return array[10][1];
}
}
我在 64 位 linux 上测试,这些是不同 64 位 oracle java 版本的结果:
1.6.0_45-b06:
Separate allocation: 401.0 ms
Allocate at once: 1.673 s
1.7.0_45-b18
Separate allocation: 408.7 ms
Allocate at once: 1.448 s
1.8.0-ea-b115
Separate allocation: 380.0 ms
Allocate at once: 1.251 s
出于好奇,我也尝试使用 OpenJDK 7(差异较小):
Separate allocation: 424.3 ms
Allocate at once: 1.072 s
对我来说这很违反直觉,我希望立即分配更快。
【问题讨论】:
-
我已经尝试了不同的尺寸和
Object[][],但没有任何改变。要么我真的瞎了,要么你发现了一些有趣的东西。或者 JIT 比我们聪明并消除了部分工作。
标签: java arrays performance