简体   繁体   English

如何通过内存堆中的java对象获取占用的空间?

[英]How can I get the occupied space by a java object in the memory heap?

How much space does an object takes from the memory heap? 对象从内存堆中占用多少空间? How can this be done? 如何才能做到这一点?

This is far more complex than just using free memory computations (which don't take into consideration garbage collections and new allocations by other threads). 这比仅使用空闲内存计算(不考虑垃圾收集和其他线程的新分配)要复杂得多。 Take a look at: 看一眼:

http://www.javaspecialists.eu/archive/Issue142.html http://www.javaspecialists.eu/archive/Issue142.html

This is advanced stuff, however. 然而,这是先进的东西。

--EDIT-- - 编辑 -

The solution above finds the deep size of an object (using a stack to traverse the reference network, a collection of visited references, and of course instrumentation). 上面的解决方案找到了一个对象的深度 (使用堆栈遍历参考网络,访问引用的集合,当然还有检测)。

However, getting the shallow size of an object is simpler, and can be achieved by java 1.5 instrumentation without extra work (see Instrumentation.getObjectSize() ). 但是,获得对象的浅层大小更简单,并且可以通过java 1.5工具实现而无需额外的工作(请参阅Instrumentation.getObjectSize() )。

The amount of memory taken by an object varies from one JVM implementation to the next and sometimes from one platform to the next. 对象占用的内存量从一个JVM实现到下一个JVM实现,有时从一个平台到下一个平台。

You can estimate the amount by counting up the number and size of primitive types and object references declared as instance variables of the object's class. 您可以通过计算原始类型的数量和大小以及声明为对象类的实例变量的对象引用来估计金额。

For example: 例如:

public class Monkey {
  int arms;
  Animal parent;
}

..has 1 object reference and 1 int primitive, which on a 32-bit architecture will take up approximately 8 bytes per instance. ..有1个对象引用和1个int原语,在32位体系结构上每个实例占用大约 8个字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM