I want to estimate the size occupied by the object. To get the size of an object, I can simply use
For this I can use Instrumentation.getObjectSize(myObject) , but this will give me a "small" size. I want to get the size of the object, including the sizes of the objects that it refers to.
My thought is that I need to get the size of the object, and then go through all the fields of the objects that are not static or primitive, and get the size for the objects they point to, and do it recursively.
Of course, I don’t want to read the size of an object several times or get stuck in a loop. Therefore, I will need to remember the objects whose size we have already calculated.
Is there a faster or more standard way to do this?
My code is as follows:
public static long getObjectSize(Object obj) { return getObjectSize(obj, new HashSet<Object>()); } private static long getObjectSize(Object obj, Set<Object> encountered) { if (encountered.contains(obj)) {
java object memory size
Gilad Jun 02 '13 at 11:24 2013-06-02 11:24
source share