What is the memory overhead of an object in Java? [duplicate]

牧云@^-^@ 提交于 2019-11-27 02:25:53

问题


Duplicate:

What is the memory consumption of an object in Java?

Assuming Java 1.6 JVM on 64-bit Linux on an Intel or AMD box, creating a simple object uses how much memory overhead in bytes? For example, each row in a 2-dimensional array is a separate object. If my array is large, how much RAM will I be using?


回答1:


That will depend on which JVM you use.

Assuming that you are not using a JVM with compressed pointers the array will consume:

  • 8 bytes for the type pointer.
  • 4 bytes for the array length.
  • 8 bytes for each element in the array (these are pointers to the actual objects).
  • Sum: 8+4+len*8 bytes
  • For a JVM with compressed pointers: 4+4+len*4 bytes

Then the actual objects that you store (references to) in the array will consume memory depending on what kind of objects they are. java.lang.Object only contains a pointer to the class, so 8 bytes, or 4 bytes if using compressed pointers.

For your own classes you can count the memory use by looking at the fields in the class. Each reference will consume 8 bytes (4 bytes for compressed pointers). Each long 8 bytes, int 4 bytes, char/short 2 byte, byte/boolean 1 byte. But all these will be aligned to an even total size that is a multiple of either 4 or 8 bytes, depending on which JVM you use.



来源:https://stackoverflow.com/questions/726404/what-is-the-memory-overhead-of-an-object-in-java

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