Ehab Yassin
Ehab Yassin

Reputation: 171

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 ?

Upvotes: 6

Views: 129

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726629

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.

Upvotes: 10

Related Questions