计算Java对象的字节大小 [英] Calculating byte-size of Java object

查看:1359
本文介绍了计算Java对象的字节大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在计算java对象[hashmap]的大小[使用的内存]。它包含[在运行时]不同数据类型的元素,因此[no-of-elem * size-of-element]不是一个好方法。现在的代码是通过一系列的

I am working on calculaitng the size [memory used] of a java object [hashmap] . It contains elements of different data types [at runtime] so [ no-of-elem * size-of-element] is not that good an approach. The code right now does it by series of

if (x)
  do something
else if (primitives)
  lookup size and calculate

然而,这个过程是CPU占用并且效率低下。

However this process is a CPU hog and in-efficient.

我正在考虑采用以下两种方法:

I am thinking of following 2 approaches instead:


  1. 将对象序列化为一个缓冲区并获得大小。

  2. 查看java.lang.instrument以获取大小

我正在寻找任何人这些方法在性能,效率,缩放等方面的经验或者如果你知道更好的方法。

I am looking for anyones experience with these approaches for performance , efficiency, scaling etc OR if you know any better way.

PS:
这是我正在构建的后台工具尺寸不需要超级准确,尽管它应该是正确的。所以我愿意换算性能的准确性

P.S: This is a background utility that I am building so the size need no be super accurate though it should be about correct. So I am willing to trade accuracy for performance

我对深度尺寸不感兴趣[不会计算这个对象所引用的对象的大小。]

I am not interested in the deep-size [the size of objects that are refered by this object will not be computed.]

我正在寻找性能比较并理解getObjectSize()如何在内部工作..所以我不会搞砸其他东西以提高性能

I am looking for a performance comparisons and understanding how getObjectSize() works internally ..so that I do not messup something else to improve the performance

谢谢

推荐答案

使用 getObjectSize()方法。

这里的实现细节:

这篇关于计算Java对象的字节大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆