简体   繁体   English

java对象数组大小

[英]java object array size

When calculate memory size of an object array, following code gives "used 24 bytes" as expected, which, as far as I know, consists of: 在计算对象数组的内存大小时,下面的代码给出了“使用过的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();
}

But when element type changed to Long (1L), the result is confusing, most of the time it's "used 9,264 bytes" , anyone can help enlighten me? 但是当元素类型改为Long(1L)时,结果令人困惑,大部分时间它都是“使用了9,264字节” ,任何人都可以帮助启发我吗? what is the difference in memory allocation between this two element type? 这两种元素类型之间的内存分配有什么不同?

// 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
}

There is a better way to calculate an object size in general, as there is a specialized tool for that, called JOL . 通常有更好的方法来计算对象大小,因为有一个专门的工具,称为JOL

It's not entirely correct how you think about it. 你怎么想它并不完全正确。 The total size of that object is going to be 40 bytes . 该对象的总大小将为40 bytes Let's see where this space is coming from: 让我们看看这个空间的来源:

12 bytes headers (8 bytes + 4 bytes, since there are two headers)

You thought it's 16 bytes ( 8 + 8 ), but there is the compressed oops option that is on by default. 您认为它是16 bytes (8 + 8),但默认情况下启用了compressed oops选项。 You can disable it via -XX:-UseCompressedOops and indeed in this case the size of the headers is going to be 16 bytes . 您可以通过-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)

So far you have 24 bytes for the array. 到目前为止,您有24 bytes的数组。

Now, you store an Integer inside it, that is an Object too, thus: 现在,您将Integer存储在其中,也就是Object,因此:

12 bytes headers
4 bytes for the actual int value inside Integer

Thus the total size is 40 bytes . 因此总大小为40 bytes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM