Java对象创建和内存大小 [英] Java object creation and memory size
问题描述
我正在尝试了解使用 new 运算符创建Java对象时将分配的大小.
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() { }
}
当我使用NewClass nc = new NewClass();
创建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?
〜杰根
推荐答案
分析是最好的方法,但是您可以像这样获得一个很好的估算值:
Profiling is the best way, but you can get a good estimate like so:
每个对象8个字节(无开销),外加字段.
8 bytes per object (bare overhead), plus fields.
- 原始字段:如Java中所列.注意:布尔值需要1个完整字节.
- 对象字段:1个指针(在32位VM上为4个字节,在64位上为8个字节),加上对象本身的大小(如果未引用现有对象)
- 数组:4个字节+元素的对象/基元
- 字符串:远远太多. IIRC,24个字节+ 2个字节/字符.可能更多.
最终结果增加到8个字节的最接近倍数.
The final result is increased to the nearest multiple of 8 bytes.
另请参阅我的示例此处,了解如何计算内存使用量在一个更复杂的对象上.注意:这些规则可能会随VM的不同而变化,并且可能会随着新版本的VM的发布而发生变化.我的估计仅适用于Sun JVM,尽管我怀疑IBM的结果将是相似的.
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.
这篇关于Java对象创建和内存大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!