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?
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.
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