HowCanIMeasureTheAmountOfMemoryNeeded

This is a rough rendering of a page from the old Prevayler wiki. Please see the new wiki for current documentation.

Hi! I would like to know how I can measure the amount of memory needed.



The best way, I think, to estimate is to create thousands of objects similar to the ones you'll have and see how much they occupy. You can use Runtime.totalMemory() minus Runtime.freeMemory() for that. -- KlausWuestefeld



The cost of loading a class is almost impossible to estimate - it depends on the structures the VM creates and the machine code that is generated (which, in the presence of adaptive optimization, depends on runtime measurements!).

The cost of a single object is much easier to estimate. In the case of HotSpot, it goes like this:

-2 words for object header (flags, class reference, object identity)
-2 words for every non-static long or double field
-1 word for every non-static field of any other type (including object types)

A word is 4 bytes (at least on 32-bit machines).

Arrays have some fixed overhead plus the size of the contents (calculated the obvious way: char arrays take up 2 bytes per element, int arrays 4 bytes per element etc).

This is the raw object size. You have to add allocation slack for unused/fragmented heap space (not sure if HotSpot additionally pads object sizes to 16 byte boundaries or something, I think it doesn't). -- StefanReich