如何计算java中的对象object大小size

 
Measuring Object Size
While the Java platform doesn't provide a way to measure the size of an object, it is possible to measure the approximate size indirectly. Section 5.1.1 discusses the Runtime methods that provide information about the size of the JVM's object heap.

You can also use these methods to determine the approximate size of an object by:

  1. Requesting garbage collection to get the heap into a known state.
  2. Measuring the free heap space.
  3. Creating an instance of the class you want to measure and keeping a reference to it.
  4. Requesting garbage collection again.
  5. Measuring the free heap space.
  6. Subtracting the second measurement from the first.

Although this general approach works, it has some flaws:

  • Garbage collection can be unpredictable.
  • Caching performed by the class when the first instance is created can skew the results.
  • The Runtime.freeSpace method might not be accurate down to the byte level.
Fortunately, you can get around most of these by:

  • Creating a primer instance of the class before your measure the heap the first time. This eliminates the impact of one-time cache costs.
  • Measuring several instances of the object and calculating the average. This helps offset the unpredictability inherent in the GC behavior and the heap space measurement methods.

zz from oracle
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值