nkukhar
nkukhar

Reputation: 2025

Why does time for initialize array 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

Second solution 115 time faster

Upvotes: 5

Views: 148

Answers (1)

dilix
dilix

Reputation: 3893

It's simplier to test int[][]

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

In this case you have to allocate size pieces of memory with size of 16 bytes.

And in this case

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

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

And allocating is expensive operation.

Upvotes: 7

Related Questions