Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a simple way to get the size of a java object?

Tags:

java

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++?

like image 468
Adam Lee Avatar asked Jan 08 '12 06:01

Adam Lee


2 Answers

There is an opensource java.SizeOf project that determines size of any of your Java object in memory.

like image 172
anubhava Avatar answered Sep 17 '22 21:09

anubhava


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.

like image 21
Stephen C Avatar answered Sep 16 '22 21:09

Stephen C