如何查找对象的大小(包括包含的对象) [英] How to find Object's size (including contained objects)

查看:76
本文介绍了如何查找对象的大小(包括包含的对象)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想估计一个对象占用的大小. 要获取对象的大小,我可以使用

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

为此,我可能会使用Instrumentation.getObjectSize(myObject),但这会给我浅"的大小.我想获取对象的大小,包括它引用的对象的大小.

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?

我的代码如下:

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;
}

推荐答案

尝试序列化对象,然后获取序列化生成的字节流的大小.如果您想知道持久化时对象的大小.

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();
}

这篇关于如何查找对象的大小(包括包含的对象)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆