由於Java規範沒有強制使用內存,這取決於您使用的JVM實現。
當然,在所有JVM實現中(例如實現運行時類型檢查)都會有每個對象的開銷。 JVM可能選擇內存對齊字段(在某些平臺上,訪問該字段時會顯着加速)。但是,如果數組成員爲內存對齊填充,並且可以確認(至少在oracle的vm for windows上)布爾值[]每個元素需要一個字節,那麼我會大吃一驚。
另外,值得注意的是,如果您碰巧遇到一個適當大的堆,引用類型字段的大小可以是8個字節。
總結:如果您真的想知道,請測量目標JVM上的內存消耗。
編輯:出於好奇,我寫了一個小的(不準確)基準:
class FourBytes {
byte a,b,c,d;
}
public class Test {
long usedBefore = used();
long used() {
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}
public void before() {
System.gc();
usedBefore = used();
}
public void after(String text) {
long usedAfter = used();
System.out.println(text + "\t" + new BigDecimal(usedAfter - usedBefore).movePointLeft(6) + " bytes");
before();
}
{
int max = 1000000;
before();
boolean[] bools = new boolean[max];
after("boolean in array");
char[] chars = new char[max];
after("char in array ");
Object[] objects = new Object[max];
after("reference type in array");
for (int i = 0; i < max; i++) {
objects[i] = new Object();
}
after("Object instance ");
Byte[] bytes = new Byte[max];
before();
for (int i = 0; i < max; i++) {
bytes[i] = new Byte((byte) i);
}
after("Byte instance ");
Integer[] integers = new Integer[max];
before();
for (int i = 0; i < max; i++) {
integers[i] = new Integer(i);
}
after("Integer instance");
FourBytes[] fbs = new FourBytes[max];
before();
for (int i = 0; i < max; i++) {
fbs[i] = new FourBytes();
}
after("FourBytes instance");
}
public static void main(String[] args) throws Exception {
new Test();
}
}
在
java version "1.7.0_02"
Java(TM) SE Runtime Environment (build 1.7.0_02-b13)
Java HotSpot(TM) Client VM (build 22.0-b10, mixed mode, sharing)
它打印:
boolean in array 1.183624 bytes
char in array 2.091768 bytes
reference type in array 4.091768 bytes
Object instance 8.023664 bytes
Byte instance 16.133408 bytes
Integer instance 16.147312 bytes
FourBytes instance 16.142568 bytes
也許鏈接實際的文章會有用嗎? – hd1