I'm trying to find out how much memory an array uses inside of the JVM. I've set up a program for that purpose, which is giving me odd results.
protected static long openMem(){
System.gc();
System.runFinalization();
return Runtime.getRuntime().freeMemory();
}
public static double listSize(int limit){
long start= openMem();
Object[] o= new Object[limit];
for(int i= 0; i<limit; i++ ){
o[i]= null;
}
long end= openMem();
o= null;
return (start-end);
}
public static void list(int i){
for(int y= 0; y<50; y++ ){
double d= Quantify.listSize(i);
System.out.println(i+" = "+d+" bytes");
}
}
public static void main(String ... args){
list(1);
list(2);
list(3);
list(100);
}
When I run this, I get two different byte-sizes for each size of array, like:
- 1 = 24.0 bytes
- 1 = 208.0 bytes
- 1 = 24.0 bytes
- 1 = 208.0 bytes
- 1 = 208.0 bytes
- 1 = 208.0 bytes
- 1 = 208.0 bytes
- 1 = 24.0 bytes
So an array of 1 element only ever returns "24 bytes" or "208 bytes", and the same pattern holds for all others:
1 = 24.0 bytes
1 = 208.0 bytes
2 = 24.0 bytes
2 = 208.0 bytes
3 = 32.0 bytes
3 = 216.0 bytes
100 = 416.0 bytes
100 = 600.0 bytes
I'm trying to figure out why that is. What I'm wondering is whether anyone else here (a) already knows the answer, or (b) knows how to find the answer.