java中获取一个对象实例的大小工具

获取对象实例的大小

对于JDK8,jdk.nashorn.internal.ir.debug.ObjectSizeCalculator

System.out.println(ObjectSizeCalculator.getObjectSize(new Object()));

低版本JDK可以借用一些工具,pom.xml中引用:

<!-- https://mvnrepository.com/artifact/com.carrotsearch/java-sizeof -->
<dependency>
    <groupId>com.carrotsearch</groupId>
    <artifactId>java-sizeof</artifactId>
    <version>0.0.5</version>
</dependency>

然后调用相应的方法就可以了:

        System.out.println(RamUsageEstimator.sizeOf(1));
        System.out.println(RamUsageEstimator.sizeOf(1L));
        System.out.println(RamUsageEstimator.sizeOf(1f));
        System.out.println(RamUsageEstimator.sizeOf(1.0));
        System.out.println(RamUsageEstimator.sizeOf(new int[]{}));
        System.out.println(RamUsageEstimator.sizeOf(new ArrayList()));
        System.out.println(RamUsageEstimator.sizeOf(new HashMap()));
        System.out.println(RamUsageEstimator.sizeOf(new Object()));  // Object对象:16bytes

获取对象实例的头信息

pom.xml中添加:

<dependency>
    <groupId>org.openjdk.jol</groupId>
    <artifactId>jol-core</artifactId>
    <version>0.8</version>
</dependency>

然后输出:

	Object a = new Object();
    System.out.println(ClassLayout.parseInstance(a).toPrintable());

结果示例:

java.lang.Object object internals:
 OFFSET  SIZE   TYPE DESCRIPTION                               VALUE
      0     4        (object header)                           01 00 00 00 (00000001 00000000 00000000 00000000) (1)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           e5 01 00 f8 (11100101 00000001 00000000 11111000) (-134217243)
     12     4        (loss due to the next object alignment)
Instance size: 16 bytes
Space losses: 0 bytes internal + 4 bytes external = 4 bytes total

以64位计算机为例:
8bytes 对象头 + 4bytes 对象指针(开启了指针压缩) + 4bytes(对齐,必须是8的倍数) = 16bytes

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值