简体   繁体   中英

Memory size of a Java 32-bit system int[] array

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?

First portion of 4 bytes takes array reference, second - array length, then what takes 8 bytes left?

Normal object overhead - typically a few bytes indicating the type of the object, and a few bytes associated with the monitor for the object. This is not array-specific at all - you'll see it for all objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM