计算对象的内存占用量,需要澄清

时间:2012-06-28 21:34:18

标签: java instrumentation

运行时

java -javaagent:ObjectSizeFetcherAgent.jar PersistentTime

我得到了

24

ObjectSizeFetcherAgent执行此操作时

public class ObjectSizeFetcher {
    private static Instrumentation  instrumentation;

    public static void premain(String args, Instrumentation inst) {
        instrumentation = inst;
    }

    public static long getObjectSize(Object o) {
        return instrumentation.getObjectSize(o);
    }
}

PersistentTime看起来如下

public class PersistentTime {

    List<String>    list    = new ArrayList<String>();

    public static void main(String[] args) {

        PersistentTime p = new PersistentTime();

        p.list.add("a");  // The number is the same with or without this
        p.list.add("b");  // The number is the same with or without this
        p.list.add("c");  // The number is the same with or without this

        System.out.println(ObjectSizeFetcher.getObjectSize(p));
    }
}

为什么在列表中添加元素没有影响?

2 个答案:

答案 0 :(得分:2)

因为getObjectSize返回(对象的实现特定近似值)对象的浅层大小。这意味着它包含列表中引用的大小,但不包括列表本身占用的空间。

答案 1 :(得分:1)

您的PersistentTime对象 一个参考(到数组列表)。

对于包含单个引用的对象,通常为24个字节。

注意:引用的对象不包含在计算中。 getObjectSize不会递归地收集组合对象大小。这通常是不可能的:可能存在无限的参考循环等;我认为不容易获得“深度”计算。

相关问题