Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 274
Simon Avatar asked Jan 30 '20 22:01

Simon


1 Answers

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.

like image 133
ave4496 Avatar answered Oct 16 '22 23:10

ave4496