10

In Java, memory used for occupying the int[] array of size n equals to (4 + n) * 4 bytes.

Practically can be proven by the code below:

public class test {

    public static void main(String[] args) {

        long size = memoryUsed();
        int[] array = new int[2000];
        size = memoryUsed() - size;
        if (size == 0)
            throw new AssertionError("You need to run this with -XX:-UseTLAB for accurate accounting");
        System.out.printf("int[2000] used %,d bytes%n", size);

    }

    public static long memoryUsed() {
        return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
    }

}

so interesting is number 4 in parentheses. First portion of 4 bytes takes array reference, second - array length, then what takes 8 bytes left?

4

1 回答 1

10

4 个字节的第一部分采用数组引用,第二个 - 数组长度,那么剩下 8 个字节呢?

正常对象开销 - 通常是几个字节,指示对象的类型,以及与对象的监视器相关联的几个字节。这根本不是特定于数组的 - 您会在所有对象中看到它。

于 2013-04-18T22:14:37.000 回答