java对象数组大小 [英] java object array size

查看:162
本文介绍了java对象数组大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在计算对象数组的内存大小时,以下代码将按预期提供已使用的24个字节" ,据我所知,该字段包括:

When calculate memory size of an object array, following code gives "used 24 bytes" as expected, which, as far as I know, consists of:

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();
}

但是当元素类型更改为Long(1L)时,结果令人困惑,在大多数情况下,它是已使用的9,264字节" ,有人可以帮助启发我吗?这两种元素类型在内存分配上有什么区别?

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? 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.

您对它的想法并不完全正确.该对象的总大小将为40 bytes.让我们看看这个空间是从哪里来的:

It's not entirely correct how you think about it. The total size of that object is going to be 40 bytes. Let's see where this space is coming from:

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

您以为它是16 bytes(8 + 8),但是默认情况下启用了compressed oops选项.您可以通过-XX:-UseCompressedOops禁用它,实际上,在这种情况下,标题的大小将为16 bytes.

You thought it's 16 bytes ( 8 + 8 ), but there is the compressed oops option that is on by default. You can disable it via -XX:-UseCompressedOops and indeed in this case the size of the headers is going to be 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)

到目前为止,该数组的位置为24 bytes.

So far you have 24 bytes for the array.

现在,您在其中存储一个Integer,也就是一个Object,因此:

Now, you store an Integer inside it, that is an Object too, thus:

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

因此,总大小为40 bytes.

这篇关于java对象数组大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆