JVM对象内存规范

本文探讨了Java对象在内存中的布局方式及其优化手段。通过合理的属性排序,可以减少内存填充,从而节省内存空间。例如,一个包含多种类型属性的类,在经过属性重排后,其内存占用可以从40字节降低到32字节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://www.codeinstructions.com/2008/12/java-objects-memory-structure.html


This scheme allows for a good optimization of memory usage. For example, imagine you declared the following class:

class MyClass {
byte a;
int c;
boolean d;
long e;
Object f;
}


If the JVM didn't reorder the attributes, the object memory layout would be like this:

[HEADER: 8 bytes] 8
[a: 1 byte ] 9
[padding: 3 bytes] 12
[c: 4 bytes] 16
[d: 1 byte ] 17
[padding: 7 bytes] 24
[e: 8 bytes] 32
[f: 4 bytes] 36
[padding: 4 bytes] 40


Notice that 14 bytes would have been wasted with padding and the object would use 40 bytes of memory. By reordering the objects using the rules above, the in memory structure of the object becomes:

HEADER: 8 bytes] 8
[e: 8 bytes] 16
[c: 4 bytes] 20
[a: 1 byte ] 21
[d: 1 byte ] 22
[padding: 2 bytes] 24
[f: 4 bytes] 28
[padding: 4 bytes] 32

This time, only 6 bytes are used for padding and the object uses only 32 bytes of memory.

通读上面的链接原文得知: java中新建一个无属性对象 花费 8byte。有属性时,object reference 占4byte.

所以大致上可以认为java中新建一个全string对象占用的内存是 (8 + string属性*4 + string属性本来占用空间)byte
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值