Java object creation and memory size

此生再无相见时 提交于 2019-12-11 13:10:32

问题


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() { }

}

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?

~ Jegan


回答1:


Profiling is the best way, but you can get a good estimate like so:

8 bytes per object (bare overhead), plus fields.

  • Primitive Fields: as listed in Java. Note: booleans need 1 full byte.
  • Object fields: 1 pointer (4 bytes on 32-bit VM, 8 on 64-bit), plus size of object itself (if not a reference to a preexisting object)
  • Arrays: 4 bytes + object/primitives for elements
  • Strings: far, far too much. IIRC, 24 bytes + 2 bytes/character. Might be more.

The final result is increased to the nearest multiple of 8 bytes.

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.




回答2:


I think you need to use a profiler to measure this. You may use JProfiler or YourKit profilers for this.



来源:https://stackoverflow.com/questions/2062553/java-object-creation-and-memory-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!