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?
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.
while an element of int array will only take 4 bytes. In total you have (16 + 8) * 100 = 240 bytes.
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];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With