How to find the size of an object (including contained objects)

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)) { // if this object was already counted - don't count it again return 0; } else { // remember to not count this object size again encountered.add(obj); } java.lang.reflect.Field fields[] = obj.getClass().getFields(); long size = Instrumentation.getObjectSize(obj); // itereate through all fields for (Field field : fields) { Class fieldType = field.getType(); // only if the field isn't a primitive if (fieldType != Boolean.class && fieldType != Integer.class && fieldType != Long.class && fieldType != Float.class && fieldType != Character.class && fieldType != Short.class && fieldType != Double.class) { // get the field value try { Object fieldValue = field.get(obj); size += getObjectSize(obj, encountered); } catch (IllegalAccessException e) {} } } return size; } 
+9
java object memory size
Jun 02 '13 at 11:24
source share
1 answer

Try serializing the object, and then get the size of the byte stream generated by serialization. what if you want to know the size of the object when it is saved.

  public static byte[] serialize(Object obj) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(obj); return baos.toByteArray(); } 
+5
Jun 06 '13 at 18:43
source share
— -



All Articles