虚拟机:Java HotSpot(TM) 64-Bit Server VM (25.221-b11, mixed mode)
对象的内存以字节为单位,且必须是8的倍数,它的构成由3部分组成:对象头+实例数据+对齐内存。对象头由2个部分组成:_mark(8字节)+oop指针。
oop指针和引用对象在开启压缩普通对象指针(-XX:+UseCompressedOops)时大小为4字节,关闭压缩普通对象指针(-XX:+UseCompressedOops)时为8字节。UseCompressedOops默认是开启的,只有虚拟机内存达到32G以上,4个字节已经无法满足寻址需求时,才需要关闭该参数。
普通基本对象大小为:
| 对象类型 | 字节 | 
| boolean | 1 | 
| byte | 1 | 
| short | 2 | 
| char | 2 | 
| int | 4 | 
| float | 4 | 
| long | 8 | 
| double | 8 | 
例1:
public class Persion { int id; }
开启压缩普通对象指针时,对象大小:(8+4)+4=16字节,是8的倍数,补齐0字节最终大小为16字节
关闭压缩普通对象指针时,对象大小:(8+8)+4=20字节,不是8的倍数,补齐4字节最终大小为24字节

例2:
public class Persion { int id; String name; int age; Date birthday; }
开启压缩普通对象指针时,对象大小:(8+4)+(4+4+4+4)=28字节,是8的倍数,补充0字节最终大小为32字节

关闭压缩普通对象指针时,对象大小:(8+8)+(4+8+4+8)=40字节,是8的倍数,补充0字节最终大小为40字节

例3:
public class Persion { int id; String name; int age; Date birthday; boolean school; } public class Student extends Persion { int b; }
开启压缩普通对象指针时:
Person对象的大小为:(12+4)+(4+4+4+4+1)=29字节,补齐3字节,最终大小为32字节
Student对象的大小为:(12+4)+(17+7)+4=40字节,补齐0字节,最终大小为40字节。

关闭压缩普通对象指针时:
Person对象的大小为:16+(4+8+4+8+1)=41字节,补齐7字节,最终大小为48字节
Student对象的大小为:16+(25+7)+4=52字节,补齐4字节,最终大小为56字节。

原文:https://www.cnblogs.com/zhi-leaf/p/11589711.html