Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Memory Overhead

I would like to ask about Memory Overhead in java, I have a large ArrayList (61,770 items), and trying to calculate the amount of memory taken by each item (counting the object and its ArrayList entry), by profiling the app i get that after all the data is loaded, the heap takes ~ 25Mb. when the ArrayList has only 2 items the heap takes ~1Mb , so roughly:

(24*1024*1024)/61,768 = 407 bytes.

however, when i count the fields of the each object, i get 148 bytes(not including the ArrayList, and assuming int=4,float=4,reference=4), I am curious to know where did all of those extra bytes came from...

i can guess that since the objects I store in the ArrayList are implementing an interface, they store extra values, maybe the VM stores a 4byte function pointer for each implemented method? the interface they implement have 20 functions so thats 80 more bytes, totaling 228 bytes, still not close to the 400 bytes measured.

any help would be appreciated.


wow, thanks for all the great answers.

@Bolo: thanks for the link ,with this class i measure ~350 bytes per object so I can least confirm the source of the large memory usage.

@Yuval A: thank you for that presentation, a valuable source of information.

@Ukko: point noted.

@Jayan: right now NetBeans profiler is giving me errors when i try to dump the heap, will try later again.

like image 747
user326841 Avatar asked Dec 22 '22 03:12

user326841


2 Answers

These results are not surprising. The JVM adds enormous amounts of overhead to each object.

About double the expected size for a single object, due to JVM memory overhead, is not uncommon.

This presentation has a wonderful, in-depth, explanation and overview of various data structure memory usage in Java.

like image 192
Yuval Adam Avatar answered Jan 07 '23 01:01

Yuval Adam


An ArrayList ist mostly bigger than the number of elements. Use getCapacity() to get the current size of the underlying array.

like image 24
ZeissS Avatar answered Jan 07 '23 00:01

ZeissS