How to find Object's size (including contained objects)

只愿长相守 提交于 2019-12-01 00:53:22

问题


I want to estimate the size taken up by an object. To get the object's size I can just use

To do so I might use Instrumentation.getObjectSize(myObject), but this will give me a "shallow" size. I want to get the size of the Object, including the sizes of the objects it references.

My thought is that I need to get the size of the object, then go through all the object's fields that are not static or primitives and get the size for the objects that they point to and do this recursively.

Of course, I don't want to count an object size a few times, or get stuck in a loop, So I'll have to remember the objects which size we already counted.

Is there a faster, or a more standard, way to do this?

My code looks like this:

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's 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's value
             try
             {
                 Object fieldValue = field.get(obj);
                 size += getObjectSize(obj, encountered);
             } 
             catch (IllegalAccessException e) {}
         }
    }
    return size;
}

回答1:


Try to serialize the object then get the size of the byte stream generated by serialization. that if you want to know the size of the object when persisted.

 public static byte[] serialize(Object obj) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(obj);
    return baos.toByteArray();
}


来源:https://stackoverflow.com/questions/16882277/how-to-find-objects-size-including-contained-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!