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
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.
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.
An initializer-list is ill-formed if the number of initializer-clauses exceeds the number of members or elements to initialize.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With