sizeof Java object [duplicate]
How can we find out the size of a Java object?
Example:
class Person{
String name;
int age;
public Person(String n, int a){
name = n;
age = a;
}
}
Person person = new Person("Andy", 30);
How can I know the size of person object?
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...
I think you can get something that might help you if you do something like this:
/* First trigger classloading */
MyObject delegate = new MyObject();
Runtime.getRuntime().gc();
long before = Runtime.getRuntime().freeMemory();
MyObject delegate2 = new MyObject();
long after = Runtime.getRuntime().freeMemory();
System.out.println("Memory used:"+(before-after));
This will hopefully give you the answer you want, or at least an approximation.