java 对象 内存大小,Java对象创建和内存大小

博客讨论了如何估算Java对象在堆中分配的大小。基本对象开销为8字节,加上字段的大小。对于基本类型字段,按照Java的字节大小计算;对于对象字段,考虑指针大小(32位VM为4字节,64位为8字节)及对象自身的大小。数组、字符串的内存占用更为复杂,字符串包括额外的开销和每个字符的大小。最终结果会向上取整到8字节的倍数。建议使用剖析工具获取准确数据。
摘要由CSDN通过智能技术生成

I am trying understand about the size that a Java object will be allocated with when created using a new operator.

Consider that i am creating a class

public class NewClass {

NewClass() { }

}

when i create an instance of NewClass using NewClass nc = new NewClass();. what is the size of the NewClass that gets created in the heap?

~ Jegan

解决方案

Profiling is the best way, but you can get a good estimate like so:

8 bytes per object (bare overhead), plus fields.

Primitive Fields: as listed in Java. Note: booleans need 1 full byte.

Object fields: 1 pointer (4 bytes on 32-bit VM, 8 on 64-bit), plus size of object itself (if not a reference to a preexisting object)

Arrays: 4 bytes + object/primitives for elements

Strings: far, far too much. IIRC, 24 bytes + 2 bytes/character. Might be more.

The final result is increased to the nearest multiple of 8 bytes.

See also my example here for how to calculate memory use on a more complex object. Note: these rules may vary with VMs, and may change as newer versions of the VM come out. My estimate only applies to the Sun JVM, although I suspect IBM's results will be similar.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值