5

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

nkukhar
  • 1,975
  • 2
  • 18
  • 37
  • 1
    How do you run this snippet? could you post the whole method? How many times have you run them? How many initial cycles did you run? Benchmarking Java operations is not a trivial thing... – ppeterka Feb 01 '13 at 09:25
  • 1
    See: http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java - The way you are doing this is unlikely to produce any meaningful results. – Brian Roach Feb 01 '13 at 09:35

1 Answers1

7

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.

dilix
  • 3,761
  • 3
  • 31
  • 55
  • 1
    115 times faster? I think this is an issue related to JVM initialization, and initial optimization process... – ppeterka Feb 01 '13 at 09:24
  • With or without optimization in 1st sample you have to store many object (array) and allocate them all in heap and in second sample there is only 2 objects – dilix Feb 01 '13 at 10:02
  • 1
    I must admit it, you're right. I created a small, proper-ish benchmark around it, and the result is (roughly) the same. I think it's time for me to do some research around it... – ppeterka Feb 01 '13 at 10:44