Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 646
Sophie Sperner Avatar asked Apr 18 '13 22:04

Sophie Sperner


People also ask

How can you calculate the memory size of an array in Java?

Memory Usage Then, it has the storage for the elements, which can be calculated by multiplying the size of the array by the data type. If the final value is not a multiple of 8 bytes, padding is added to make it a multiple of 8. So the size of the array is 12 + 10 * 4 + 4 = 56 bytes.

How much memory does an int array take?

while an element of int array will only take 4 bytes. In total you have (16 + 8) * 100 = 240 bytes.

What is array memory in Java?

Arrays are used to store multiple values ​​in a single variable, instead of declaring separate variables for each value. In Java, an array stores primitive values ​​(int, char, etc) or references (i.e. pointers) to objects. Single-dimension Array: int arr[] = new int[5];


1 Answers

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.

like image 138
Jon Skeet Avatar answered Sep 24 '22 13:09

Jon Skeet