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?
To summarize, duplicate objects, i.e. multiple instances of the same class with identical contents, can become a burden in a Java app. They may waste a lot of memory and/or increase the GC pressure. The best way to measure the impact of such objects is to obtain a heap dump and use a tool like JXRay to analyze it.
Minimum object size is 16 bytes for modern 64-bit JDK since the object has 12-byte header, padded to a multiple of 8 bytes. In 32-bit JDK, the overhead is 8 bytes, padded to a multiple of 4 bytes.
A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.
Similarly, there is no sizeof() operator in Java. All primitive values have a predefined size, like int is 4 bytes, char is 2 byte, short is 2 byte, long and float is 8 byte, and so on.
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:
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*yMaybe 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With