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

对着背影说爱祢 提交于 2019-11-28 08:46:44

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.

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