Two-dimensional array distribution performance

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.

+6
source share
1 answer

Absolute incredible. The test source may suffer from optimization, gc and JIT, but is that?

Looking at the java byte code instruction set :

  • anewarray (+ 2 byte indirect class index) for object class arrays (a = address)
  • newarray (+ 1 byte for the prinitive class) for arrays of primitive types
  • multianewarray (+ indirect byte class index 2) for multidimensional arrays

This makes us suspect that multianewarray is suboptimal for primitive types.

Before looking any further, I hope someone knows where we are misled.

+1
source

Source: https://habr.com/ru/post/971075/


All Articles