How to calculate the amount of space occupied by Java objects?
There is no sizeof operator in Java, so there is no way to know how much space an object occupies, but there are some basic rules when allocating objects, based on these rules, we can determine the object size.
Object Header
The object header has at least two words. If it is an array, the three words have the following content:
Rules
First, all objects are 8-byte aligned. attributes are stored in the order of [long, double], [int, float], [char, short], [byte, boolean], and reference, for example:
- public class Test {
- byte a;
- int b;
- boolean c;
- long d;
- Object e;
- }
If the attributes of this object are stored in sequence, the occupied space is: head (8) + a (1) + padding (3) + B (4) + c (1) + padding (7) + d (8) + e (4) + padding (4) = 40. But according to this rule, we can get: head (8) + d (8) + B (4) + a (1) + c (1) + padding (2) + e (4) + padding (4) = 32. We can see that it saves a lot of space.
When an inheritance relationship is involved, there is a basic rule: first, store the members in the parent class, and then the members in the subclass. For example:
- class A {
- long a;
- int b;
- int c;
- }
- class B extends A {
- long d;
- }
The storage sequence and occupied space are as follows: head (8) + a (8) + B (4) + c (4) + d (8) = 32. What if the attributes in the parent class are less than eight bytes? In this way, there is a new rule: if the interval between the last member of the parent class and the first member of the subclass is less than four bytes, then the basic unit of the four bytes needs to be extended, for example:
- class A {
- byte a;
- }
- class B extends A {
- byte b;
- }
The occupied space is as follows: head (8) + a (1) + padding (3) + B (1) + padding (3) = 16. Obviously, this method is a waste of space. If the first member of the subclass is double or long, and the parent class does not use up 8 bytes, JVM will destroy the rule to fill the space with small data. For example:
- class A {
- byte a;
- }
- class B extends A {
- long b;
- short c;
- byte d;
- }
The occupied space is as follows: head (8) + a (1) + padding (3) + c (2) + d (1) + padding (1) + B (8) = 24.