Simon
Simon

Reputation: 93

Switching out array sizes in 2d array takes different amount of memory

I declared a 2d-array matrix in Java of type byte. When checking the memory used with the dimensions (10^6 x 4) it was drastically different from the same size matrix but with dimensions (4 x 10^6).

// Measure memory before matrix initialization -> 2MB
System.out.println("Meg used="+(Runtime.getRuntime().totalMemory()-
 Runtime.getRuntime().freeMemory())/(1000*1000)+"M");

byte[][] test = new byte[4][1000000]; // init

// Measuring memory after -> 6MB as expected
System.out.println("Meg used="+(Runtime.getRuntime().totalMemory()-
 Runtime.getRuntime().freeMemory())/(1000*1000)+"M");
// Measure memory before matrix initialization -> 2MB
System.out.println("Meg used="+(Runtime.getRuntime().totalMemory()-
 Runtime.getRuntime().freeMemory())/(1000*1000)+"M");

byte[][] test = new byte[1000000][4]; // init

// Measuring memory after -> 30MB
System.out.println("Meg used="+(Runtime.getRuntime().totalMemory()-
 Runtime.getRuntime().freeMemory())/(1000*1000)+"M");

In the first case I get 6MB so the array takes 4MB as expected. However in the second case the matrix takes 28MB. Why are they not equal?

Upvotes: 6

Views: 136

Answers (1)

ave4496
ave4496

Reputation: 3018

It's the overhead that makes the difference. For every array Java has to save information. It's just 4 long arrays vs. 1000000 short arrays.

Upvotes: 4

Related Questions