Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 321
nkukhar Avatar asked Feb 01 '13 08:02

nkukhar


People also ask

Does initializing an array take o n time?

In order to initialize an array, you need to pass over all its cells and put there a zero, as the default initial value. That process takes O(n) time, whereas n = array_size.

What is run time array initialization?

Run time Array initialization Using runtime initialization user can get a chance of accepting or entering different values during different runs of program. It is also used for initializing large arrays or array with user specified values. An array can also be initialized at runtime using scanf() function.

What happens when an array is initialized with more Initializers as compared to its size?

An initializer-list is ill-formed if the number of initializer-clauses exceeds the number of members or elements to initialize.

What is the difference between compile time initialization and runtime initialization in arrays?

Compile time is the period when the programming code (such as C#, Java, C, Python) is converted to the machine code (i.e. binary code). Runtime is the period of time when a program is running and generally occurs after compile time.


1 Answers

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.

like image 148
dilix Avatar answered Sep 21 '22 16:09

dilix