I am wondering why the distribution of a 2D array immediately ( new int[50][2] ) is worse than allocating separately, that is, execute new int[50][] first, and then new int[2] one after another. Here is an unprofessional reference code:
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]; } }
I tested on 64-bit Linux, these are the results with various 64-bit versions of oracle :
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
Just for curiosity, I tried it with OpenJDK 7 (where the difference is less):
Separate allocation: 424.3 ms Allocate at once: 1.072 s
For me, this is completely contradictory, I would expect that the selection will be faster immediately.
source share