How do I calculate how much space a Java object takes up?

  • 2020-04-01 04:36:26
  • OfStack

This article describes how to calculate how much space a Java object takes up

Object header

At least two words are in the header of the object. If it is an array, then three words are as follows:

1. Object HashCode, lock information, etc
2. Pointer to object type data
3. The length of the array (if it is an array)

Second, the rules

First, any object is 8-byte aligned, and 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 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 following this rule you get: head(8) + d(8) + b(4) + a(1) + c(1) + padding(2) + e(4) + padding(4) = 32. You can see there's a lot of space saved.

One of the most basic rules when it comes to inheritance is to first store the members of the parent class, then the members of the subclass. For example:


class A {
  long a;
  int b;
  int c;
}
class B extends A {
  long d;
}

The storage order and space are as follows: head(8) + a(8) + b(4) + c(4) + d(8) = 32. What if the attributes in the parent class are not eight bytes long? Here's a new rule: if the last member of a parent class is not spaced 4 bytes from the first member of a subclass, you need to extend to the base unit of 4 bytes. For example:


class A {
  byte a;
}
class B extends A {
  byte b;
}

So here's the amount of space: head(8) + a(1) + padding(3) + b(1) + padding(3) = 16. If the first member of a subclass is a double or long, and the parent does not use up to 8 bytes, the JVM breaks the rule and populates the space with smaller data. For example:


class A {
  byte a;
}
class B extends A {
  long b;
  short c;
  byte d;
}

Head (8) + a(1) + padding(3) + c(2) + d(1) + padding(1) + b(8) = 24.

This is how to calculate how much space Java objects take up. I hope it will help you learn Java programming.


Related articles: