views:

68

answers:

3

Hi there.

I'm in the process of learning Java, I'm reading the Head First Java book and I think it's great so far... However, one thing I really like to know is how much space does an object takes from the memory heap, you know... bits, bytes, kb, etc. How can this be done?

This is my first question here... I hope isn't a stupid question, and also sorry for my english skills, Thanks.

+1  A: 

This StackOverflow thread I believe answers your question - in particular, as of java 1.5, the instrumentation package can provide this

http://stackoverflow.com/questions/52353/in-java-what-is-the-best-way-to-determine-the-size-of-an-object

Pete
+1 Cool beans :)
fd
Thank you! I couldn't find that question, thanks again.
eiefai
+1  A: 

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()).

Eyal Schneider
I think this is too much for now, Pete's answers works for me. Thanks.
eiefai
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.
eiefai
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?
eiefai
@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
A: 

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.

fd
Yeah, I did think of that, but seemed too clumsy, thanks anyway
eiefai