General formula for calculating memory usage
In general, the heap memory used by a Java object in Hotspot consists of:
- an object header, consisting of a few bytes of "housekeeping" information;
- memory for primitive fields, according to their size ;
- memory for reference fields (4 bytes each);
- padding: potentially a few "wasted" unused bytes after the object data, to make every object start at an address that is a convenient multiple of bytes and reduce the number of bits required to represent a pointer to an object.
Java type Bytes required boolean 1 byte char 2 short int 4 float long 8 double
- a normal object requires 8 bytes of "housekeeping" space;
- arrays require 12 bytes (the same as a normal object, plus 4 bytes for the array length).
Object size granularity
In Hotspot, every object occupies a number of bytes that is a multiple of 8. If the number of bytes required by an object for its header and fields is not a multiple 8, then you round up to the next multiple of 8.
This means, for example, that:
- a bare Object takes up 8 bytes;
- an instance of a class with a single boolean field takes up 16 bytes: 8 bytes of header, 1 byte for the boolean and 7 bytes of "padding" to make the size up to a multiple of 8;
- an instance with eight boolean fields will also take up 16 bytes: 8 for the header, 8 for the booleans; since this is already a multiple of 8, no padding is needed;
- an object with a two long fields, three int fields and a boolean will take up:
- 8 bytes for the header;
- 16 bytes for the 2 longs (8 each);
- 12 bytes for the 3 ints (4 each);
- 1 byte for the boolean;
- a further 3 bytes of padding, to round the total up from 37 to 40, a multiple of 8.
Post a Comment