Why the time to initialize the array is different

Why

        long t = System.currentTimeMillis();
        int size = 3333333;
        int[][][] arr = new int[size][6][2];
//        int[][][] arr= new int[2][6][size];
        pr(System.currentTimeMillis() - t );

prints 5000 ms but

        long t = System.currentTimeMillis();
        int size = 3333333;
//        int[][][] arr = new int[size][6][2];
        int[][][] arr= new int[2][6][size];
        pr(System.currentTimeMillis() - t );

prints 44 ms

The second solution is 115 times faster

+5
source share
1 answer

Easier to check int[][]

int[][] arr = new int[size][2];

In this case, you need to allocate sizememory fragments of 16 bytes in size.

And in this case

int[][] arr = new int[2][size];

you need to allocate only 2 pieces of memory * 8 bytes in size.

And isolation is an expensive operation.

+6
source

All Articles