This article introduces the method of calculating how much space Java objects occupy. It is shared with you for your reference. The specific content is as follows
1. Object head
There are at least two WORDs at the head of the object. If it is an array, then three WORDs are as follows:
II. Rules
First, any object is 8 bytes aligned, and the properties 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 properties of this object are stored in order, the space to be occupied 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 get: head(8) + d(8) + b(4) + a(1) + c(1) + padding(2) + e(4) + padding(4) = 32. You can see that it saves a lot of space.
When it comes to inheritance relationships, there is a basic rule: first, the members in the parent class are stored, and then the members in the subclass are stored. For example:
class A { long a; int b; int c;}class B extends A { long d;}The order and space occupied in this way are as follows: head(8) + a(8) + b(4) + c(4) + d(8) = 32. So what if the attributes in the parent class are not enough eight bytes? This gives a new rule: If the interval between the last member of the parent class and the first member of the child class is not enough for 4 bytes, it needs to be expanded to the basic unit of 4 bytes, for example:
class A { byte a;}class B extends A { byte b;}Then the space occupied at this time is as follows: head(8) + a(1) + padding(3) + b(1) + padding(3) = 16. Obviously this method is rather wasteful, so there is: if the first member of the subclass is double or long, and the parent class does not use up 8 bytes, the JVM will break the rules and fill smaller data into the space, for example:
class A { byte a;}class B extends A { long b; short c; byte d;}The space occupied at this time is as follows: head(8) + a(1) + padding(3) + c(2) + d(1) + padding(1) + b(8) = 24.
The above is the method of calculating how much space Java objects occupy. I hope it will be helpful for everyone to learn Java programming.