有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java不使用探查器,对象有多大

Possible Duplicate:
In Java, what is the best way to determine the size of an object?

我在网上找到了这段代码:

static Runtime runtime = Runtime.getRuntime();
...
long start, end;
Object obj;
runtime.gc();
start = runtime.freememory();
obj = new Object(); // Or whatever you want to look at
end =  runtime.freememory();
System.out.println("That took " + (start-end) + " 
bytes.");

但它不是很可靠,有没有办法做得更好


共 (2) 个答案

  1. # 1 楼答案

    我有一点测量物体大小的经验,我学到的一件事是不要相信探查器。它不会给出实际的测量值,但会对进行估计。为了使这一点非常具体,它在64位虚拟机上100%错误地判断了参考数组的大小:在实际大小为每个插槽32位的情况下,它猜测的是64位

    只要你非常小心地熟悉你的特定配置,并确保得到一致的结果,你的测量方法实际上是很好的。还有一些建议:

    1. 永远不要测量单个对象的大小,而是测量一千个或一百万个对象的数组的大小。在对象之间共享数据的情况下(一个非常典型的场景),这对于提供更现实的结果非常重要。更改数组大小,以确保每个对象的结果始终相同

    2. 在分配数组之前和之后做两到三个System.gc(),在它们之间暂停半秒钟左右

    3. 不要只测量freeMemory,因为堆可以增长;测量totalMemory() - freeMemory()

  2. # 2 楼答案

    JVM分块分配内存,这样就可以跨线程并发执行。这被称为Thread-Local Allocation Buffer

    TLAB - Thread-local allocation buffer. Used to allocate heap space quickly without synchronization. Compiled code has a "fast path" of a few instructions which tries to bump a high-water mark in the current thread's TLAB, successfully allocating an object if the bumped mark falls before a TLAB-specific limit address.

    如果使用-XX:-UseTLAB关闭此选项,您将获得更准确的内存使用信息

    public static void main(String... args) {
        for (int i = 0; i < 10; i++) {
            long used1 = memoryUsed();
            new Object();
            long used2 = memoryUsed();
            System.out.println(used2 - used1);
        }
    }
    
    public static long memoryUsed() {
        return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
    }
    

    使用默认选项打印

    0 0 0 0 0 0 0 0 0 0

    -XX:-UseTLAB

    十六 16 16 16 16 16 16 16 16 十六