鄭无爲*_*鄭无爲 5 java arrays object
在计算对象数组的内存大小时,下面的代码按预期给出"使用过的24个字节",据我所知,它包括:
4bytes(element pointer)+16bytes(object header)+4bytes(element space) = 24bytes
// with JVM argument -XX:-UseTLAB
public static void main(String[] args) {
long size = memoryUsed();
Object[] o = new Object[]{1};
//Object[] o = new Object[]{1L};
size = memoryUsed() - size;
System.out.printf("used %,d bytes%n", size);
//Output: used 24 bytes
}
public static long memoryUsed() {
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}
Run Code Online (Sandbox Code Playgroud)
但是当元素类型改为Long(1L)时,结果令人困惑,大部分时间它都是"使用了9,264字节",任何人都可以帮助启发我吗?这两种元素类型之间的内存分配有什么不同?
// with JVM argument -XX:-UseTLAB
public static void main(String[] args) {
long size = memoryUsed();
//Object[] o = new Object[]{1};
Object[] o = new Object[]{1L};
size = memoryUsed() - size;
System.out.printf("used %,d bytes%n", size);
//Output: used 9,264 bytes
}
Run Code Online (Sandbox Code Playgroud)
一般来说,有一种更好的方法来计算对象大小,因为有一个专门的工具,称为JOL。
你的想法并不完全正确。该对象的总大小将为40 bytes。让我们看看这个空间来自哪里:
12 bytes headers (8 bytes + 4 bytes, since there are two headers)
Run Code Online (Sandbox Code Playgroud)
您认为它是16 bytes( 8 + 8 ),但默认情况下有一个compressed oops选项处于打开状态。您可以通过禁用它-XX:-UseCompressedOops,实际上在这种情况下,标头的大小将为16 bytes.
4 bytes size of the array (arrays have an int size that is stored in headers)
4 bytes is the reference size of the Integer (1)
4 bytes alignment (since objects are 8 bytes aligned - this is the trick behind CompressedOops btw)
Run Code Online (Sandbox Code Playgroud)
到目前为止你已经有了24 bytes数组。
现在,您在其中存储一个整数,它也是一个对象,因此:
12 bytes headers
4 bytes for the actual int value inside Integer
Run Code Online (Sandbox Code Playgroud)
因此总大小为40 bytes.
| 归档时间: |
|
| 查看次数: |
640 次 |
| 最近记录: |