I have noticed that initializing 2D array like this
case 1 :-
int ar [] [] = new int [10000001][10] ;
taking more time than initializing it like this
case 2 :-
int ar[] [] = new int [10] [10000001] ;
in case 1 it toke time around 4000ms but in case 2 it does not exceed 100ms why there is this big gap ?
Strictly speaking, Java does not have 2D arrays: instead, it uses 1D arrays arranged into 1D arrays of arrays.
In your first case, in addition to the single array of arrays, Java makes 10000001 arrays of 10 elements, while in the second case it makes 10 arrays of 10000001 elements.
Since the number of objects differs by a factor of million, the first case is significantly slower.
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