演示计算jvm中对象占用多少内存
引入依赖
<dependency>
<groupId>org.openjdk.jol</groupId>
<artifactId>jol-core</artifactId>
<version>0.10</version>
</dependency>
编写测试类
package org.example;
import org.openjdk.jol.info.ClassLayout;
public class Test1 {
public static void main(String[] args) {
System.out.println(ClassLayout.parseInstance(new Object()).toPrintable());
Entity entity = new Entity();
entity.setAddress(new Address());
System.out.println(ClassLayout.parseInstance(entity).toPrintable());
}
public static class Entity{
int age;
int sex;
Address address;
public void setAddress(Address address) {
this.address = address;
}
}
public static class Address{
String city;
}
}
查看结果
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
org.example.Test1$Entity 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) d5 cb 00 f8 (11010101 11001011 00000000 11111000) (-134165547)
12 4 int Entity.age 0
16 4 int Entity.sex 0
20 4 org.example.Test1.Address Entity.address (object)
Instance size: 24 bytes
Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
得出结论
对象占用内存分为:对象头、对象体、对齐填充
- 对象头分为:MarkWord、KlassWork、数组长度(可选)
MarkWord:用于存储对象运行的数据,比如HashCode、锁状态标志、GC分代年龄等。
KlassWork:对象指向它的类元数据的指针
数组长度:这部分只有是数组对象才有,如果是非数组对象,就没这部分了
这部分在64位操作系统下,占8字节(64bit),在32位操作系统下,占4字节(32bit)。在JVM在1.6之后,在64位操作系统下都是默认开启指针压缩均占用4字节 - 对象体:基本数据类型除long和double以外占4个字节、long和double占8个字节、引用数据类型占用4个字节
- 对齐填充:64bit的机器对象占用的内存是8的倍数,不足时填充、32bit的机器对象占用的内存是4的倍数,不足时填充
CPU是按块读取的,没有内存对齐的数据读取的内存块会包含不需要的字节,内存需要移除不需要的字节之后再合并。内存对齐后就不需要额外的计算。
参考文献:https://blog.csdn.net/dl962454/article/details/116933443