获取对象实例的大小
对于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