在Java中,用于占用大小为n
的int[]
数组的内存等于(4 + n) * 4
字节。
实际上可以通过下面的代码来证明:
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();
}
}
非常有趣的是括号中的数字4
。 4
字节的第一部分获取数组引用,第二部分 - 数组长度,那么剩下的 8 个字节是什么?
最佳答案
First portion of 4 bytes takes array reference, second - array length, then what takes 8 bytes left?
普通对象开销 - 通常是几个字节,指示对象的类型,以及与对象监视器相关联的几个字节。这根本不是特定于数组的 - 您会在所有对象中看到它。
关于java - Java 32 位系统 int[] 数组的内存大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16093938/