sizeof java对象 [英] sizeof java object

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

问题描述

我们怎样才能找出java对象的大小?

How can we find out the size of a java object??

示例:

class Person{
    String name;  
    int age;  

    public Person(String n, int a){  
        name = n;  
        age = a;  
    }
}  

Person person = new Person("Andy", 30);  

现在怎样才能知道人物对象的大小?

now how can I know the size of person object??

谢谢

推荐答案

这个问题没有意义,至少没有进一步的上下文。

The question is not meaningful, at least not without further context.

Java中大小的概念只能在原语中得到合理定义:一个字节是8位(不足为奇)一个 int 是32位, 64位等(参见例如 http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html 获取完整列表。)

The notion of "size" in Java is only reasonably well defined for primitives: A byte is 8 bit (unsurprisingly) an int is 32 bit, a long 64bit, etc. (see e.g. http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html for a full list).

对于对象实例,它更复杂,因为:

For object instances, it's more complicated, because:


  • 对象实例可以(并且通常会在内部包含对其他实例的引用,因此您必须决定是否计算这些依赖实例以及如何计算。如果多个实例共享依赖项怎么办?

  • 有时,对象实例可能会被重用(例如 java.lang.String 的实习,请参阅 http://en.wikipedia.org/wiki/String_interning )。因此,如果使用大小为y的x对象,则总大小可能小于x * y

  • JVM在如何在内部实现对象和实例方面有很大的余地。
    它可能对不同的实例使用不同的技术(例如共享内部数据结构),因此甚至可能没有一个有意义的大小来分配给单个对象。

  • Object instances can (and usually will) contain references to other instances internally, so you must decide whether to count these dependent instances, and how. What if several instances share a dependency?
  • Sometimes, object instances may be reused (e.g. interning of java.lang.String, see http://en.wikipedia.org/wiki/String_interning ). So if you use x objects of size y, the total size may be smaller than x*y
  • The JVM has a lot of leeway about how to implement objects and instances internally. It may use different techniques for different instances (e.g. sharing internal data structures), so there may not even be a meaningful "size" to assign to a single object.

也许您可以解释为什么您对对象大小感兴趣。

Maybe you could explain why you are interested in object sizes.

估算使用的堆内存有一些经验法则通过实例(例如在Sun JVM中, java.lang.Object 实例使用8个字节),但这些将取决于您使用的JVM。

There are some rules of thumb for estimating the heap memory used by instances (e.g. in the Sun JVM, a java.lang.Object instance uses 8 byte), but these will depend on the JVM you use.

通常,如果您想了解堆的使用情况,请使用内存/堆分析器。

Generally, if you want to know about your heap usage, use a memory / heap profiler.

编辑:

嗯,(从JDK 6开始)有一种方法来获得对象使用的内存量的近似值: http://download.oracle。 COM / JavaSE的/ 6 /文档/ API /爪哇/郎/仪器/ Instrumentation.html#getObjectSize%28java。 lang.Object%29

Well, there is (as of JDK 6) a way to get an approximation of the amount of memory used by an object: http://download.oracle.com/javase/6/docs/api/java/lang/instrument/Instrumentation.html#getObjectSize%28java.lang.Object%29

它仍然只是一个近似...

It's still only an approximation...

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

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