Java Object Size and Overhead
Let's look at the details few
details of object header and calculate the memory size an object occupies
inside JVM Heap.
Each Object contains
following information.
• The Object Header.
• The memory for primitive
types.
• The memory for reference
types.
• Offset / alignment - in fact, these are a few unused bytes that are placed after the
data object itself. This is done in order that an address in memory was always
a multiple of machine word, to speed up the memory read + reduce the number of
bits for a pointer to an object. It is also worth noting that in java a size of
any object is multiple of 8 bytes!
• Object Header :
In case of 32-bit
system, the header size is 8 bytes, in the case of 64-bit system, respectively
is 16 bytes. It contains following information.
1 Hash Code -
2 Garbage Collection
Information - each java
object contains the information needed for the memory management.
3 Type Information Block Pointer - contains information about the type
of object. This block contains information about the virtual method table, a
pointer to an object that represents the type and pointers to some additional
structure for more efficient call interfaces, and dynamic type checking.
4 Lock - each object contains information about the
locking.
5 Array Length - if the object - an array, then the header
extends by 4 bytes to store the length of the array.
Lets calculate the size of
Integer and String on 32-bit HotSpot JVM.
We can Use JOL
Tool to find the object's sizes.
Integer:
Header: 8 bytes
|
Field int: 4 bytes
|
Alignment for the multiplicity of 8
: 4 byte (padding)
|
Total: 16 bytes
To store 4 bytes of Integer, we
are using 16 bytes of space(12 bytes extra)
|
String:
new String ()
|
Header: 8 bytes
|
Fields int: 4 bytes * 3 == 12 bytes
(1. an integer offset into
the array at which the string starts;
2.the length of the string;
3. another int for the cached calculation of the hash code.)
|
The reference variable to an object
of array: 4 bytes
|
Total: 24 bytes
|
Other Objects : new char [1]
|
Header: 8 bytes + 4 bytes for the
array length == 12 bytes
|
Primitives char: 2 bytes * 1 == 2
bytes
|
Alignment for the multiplicity of 8
: 2 bytes
|
Total: 16 bytes
|
Total, the new String
("a") = 24+16 = 40 bytes
To store 1 bytes of Character,
we are using 40 bytes of space(12 bytes extra)
If you are
dealing with 1 billion strings , it is going to occupy 40GB of memory.
|
Comments
Post a Comment