How much memory does a Java Array use? -
i'm trying find out how memory array uses inside of jvm. i've set program purpose, 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 run this, 2 different byte-sizes 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 array of 1 element ever returns "24 bytes" or "208 bytes", , same pattern holds 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 figure out why is. i'm wondering whether else here (a) knows answer, or (b) knows how find answer.
measuring heap occupancy on jvm trickier measuring performance. one, there thread-local allocation buffers (tlabs), chunks of heap allocated @ once regardless of object size being allocated. should disable use measurement: -xx:-usetlab
. further, code things right others right. example suggest running two gc's; no need run finalization; , run gc before allocation, after deallocation. run before each measurement. need use totalmemory-freememory
, otherwise vulnerable heap resizing.
all in all, try measuring code, gives me reliable results.
class quantify { static final object[][] arrays = new object[20][]; static long takenmem(){ final runtime rt = runtime.getruntime(); return rt.totalmemory() - rt.freememory(); } static long arraysize(int size){ system.gc(); system.gc(); long start = takenmem(); (int = 0; < arrays.length; i++) arrays[i] = new object[size]; final long end = takenmem(); (int = 0; < arrays.length; i++) arrays[i] = null; system.gc(); system.gc(); return (end - start) / arrays.length; } public static void main(string... args) { (int = 1; <= 20; i++) system.out.println(i+": "+arraysize(i)); } }
i output:
1: 24 2: 24 3: 32 4: 32 5: 40 6: 40 7: 48 8: 48 9: 56 10: 56 11: 64 12: 64 13: 72 14: 72 15: 80 16: 80 17: 88 18: 88 19: 96 20: 96
this consistent real situation: minimum allocation 24 bytes due overhead of headers; sizes change 8 due memory alignment concerns (this typical 64-bit jvm).
Comments
Post a Comment