The question is not meaningful, at least not without further context.
The notion of "size" in Java is only reasonably well defined for primitives: A byte is 8 bit (unsurprisingly) an int
is 32 bit, a long
64bit, etc. (see e.g. http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html for a full list).
For object instances, it's more complicated, because:
- Object instances can (and usually will) contain references to other instances internally, so you must decide whether to count these dependent instances, and how. What if several instances share a dependency?
- Sometimes, object instances may be reused (e.g. interning of
java.lang.String
, see http://en.wikipedia.org/wiki/String_interning ). So if you use x objects of size y, the total size may be smaller than x*y
- The JVM has a lot of leeway about how to implement objects and instances internally.
It may use different techniques for different instances (e.g. sharing internal data structures), so there may not even be a meaningful "size" to assign to a single object.
Maybe you could explain why you are interested in object sizes.
There are some rules of thumb for estimating the heap memory used by instances (e.g. in the Sun JVM, a java.lang.Object
instance uses 8 byte), but these will depend on the JVM you use.
Generally, if you want to know about your heap usage, use a memory / heap profiler.
Edit:
Well, there is (as of JDK 6) a way to get an approximation of the amount of memory used by an object: http://download.oracle.com/javase/6/docs/api/java/lang/instrument/Instrumentation.html#getObjectSize%28java.lang.Object%29
It's still only an approximation...
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…