I would like to know any simple way to retrieve the size of a java object? Also, anyway to get the size of a class like sizeof operator in c++?
There is an opensource java.SizeOf project that determines size of any of your Java object in memory.
The Instrumentation interface has a getObjectSize() method.
However this only gives you the size of the object itself, not its component subobjects. So for instance, it will tell you that all String
objects are the same size.
Another problem is that the size of an object can actually change spontaneously. For instance, if you get the identity hashcode of an object and it survives a GC cycle, then its size will be increased by (at least) 4 bytes to store the identity hashcode value.
The problem of finding the size of "an object" is that it is impossible for a general utility class / method to know for sure where the abstraction boundaries of an arbitrary object are. There are problems for something even as simple as the String class. (Consider String objects created using substring(...)
in Java 6. Do you could the char[] value
object as a part of this
, or part of the original String, or both? What does this mean for the sizes of the respective objects?)
Thus, it is inevitable that something like net.sourceforge.sizeof
cannot give an entirely accurate accounting of space usage.
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