How much space does an object takes from the memory heap? How can this be done?
2 Answers
This is far more complex than just using free memory computations (which don't take into consideration garbage collections and new allocations by other threads). Take a look at:
http://www.javaspecialists.eu/archive/Issue142.html
This is advanced stuff, however.
--EDIT--
The solution above finds the deep size of an object (using a stack to traverse the reference network, a collection of visited references, and of course instrumentation).
However, getting the shallow size of an object is simpler, and can be achieved by java 1.5 instrumentation without extra work (see Instrumentation.getObjectSize()).

- 22,166
- 5
- 47
- 78
-
I think this is too much for now, Pete's answers works for me. Thanks. – Eduardo Rascon Jul 20 '10 at 22:57
-
I was checking the code from Pete's answer link and noticed the line that reads instrumentation.getObjectSize(); I'm now checking the Intrumentation class, thanks again. – Eduardo Rascon Jul 22 '10 at 18:08
-
One thing, Instrumentation is an interface or a static class like Math? the link you gave me says "public interface Instrumentation" but you will have to code your own implementation of getObjectSize() if really its an interface, right? – Eduardo Rascon Jul 22 '10 at 18:50
-
@eiefai: the fact that Instrumentation is an interface does not mean that YOU must provide an implementation... there is an implementation available for you. Follow the instructions in the link, or in Pete's answer. – Eyal Schneider Jul 22 '10 at 20:25
The amount of memory taken by an object varies from one JVM implementation to the next and sometimes from one platform to the next.
You can estimate the amount by counting up the number and size of primitive types and object references declared as instance variables of the object's class.
For example:
public class Monkey {
int arms;
Animal parent;
}
..has 1 object reference and 1 int primitive, which on a 32-bit architecture will take up approximately 8 bytes per instance.

- 10,674
- 3
- 31
- 46
-
Yeah, I did think of that, but seemed too clumsy, thanks anyway – Eduardo Rascon Jul 20 '10 at 22:52