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

2
  • 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... Commented Feb 1, 2013 at 9:25
  • 1
    See: stackoverflow.com/questions/504103/… - The way you are doing this is unlikely to produce any meaningful results. Commented Feb 1, 2013 at 9:35

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

115 times faster? I think this is an issue related to JVM initialization, and initial optimization process...
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
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...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.