views:

764

answers:

1

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?

+4  A: 

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.

thobe