Sophie Sperner
Sophie Sperner

Reputation: 4556

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?

Upvotes: 10

Views: 1580

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500903

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.

Upvotes: 10

Related Questions