Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is java taking long time initializing two dimensional arrays starting with the first dimension having a big size number?

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 ?

like image 790
Ehab Yassin Avatar asked Apr 18 '17 12:04

Ehab Yassin


1 Answers

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.

like image 157
Sergey Kalinichenko Avatar answered Sep 18 '22 22:09

Sergey Kalinichenko