【发布时间】:2013-04-12 05:11:32
【问题描述】:
在 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 个字节呢?
【问题讨论】: