To figure out how much space an instance object takes up, you first need to know Java’s data types.

Java data types are divided into reference data types and primitive data types.

A reference data type consists of a reference variable (refvar) and the actual object to which it points.

A reference variable is a basic data type that holds a reference to the memory address of the actual object, which is stored in the heap.

This also explains why Java methods pass arguments only by value, because they simply assign a memory address pointing to an object to a local reference variable in a method argument, unlike C++ reference passing.

Nine basic data types

type The size of the
boolean 1B
byte 1B
char 2B
short 2B
int 4B
long 8B
float 4B
double 8B
refvar 4B

Why is Boolean type 1B and not 1bit?

That’s because the smallest unit of computer data processing is a byte, so although booleans actually use only one bit, they need to add zeros from the other seven bits to make up one byte.

The basic concept

Before you start counting, there are a few concepts to understand:

Object head

It consists of two parts:

  1. Object tags (hash code, GC tag, GC word count, synchronous lock tag, bias lock holder), occupy 8B.
  2. Class meta information (class meta information is a reference to its class metadata Klass), the reference is 4B.

Alignment filling

In other words, the allocated space must be a multiple of 8B. If only 12B is used, 16B is also allocated.

Computing space footprint

class Demo {
    // +12B Object header occupation
    // +1B
    byte b;
    / / + 4 b references
    Object obj1;
    // even if the reference refers to an object, it still takes up only the space of the reference itself.
    Object obj2 = new Object();
    // +4B where the array is also a reference type, the actual array object is in the heap
    double[] d = new double[1000];
}
Copy the code

So this works out to be 25B, and according to the alignment fill rule, you have to allocate 32B.

Reference: The Manual for Coding Efficient Java Development


Thank you for reading this article, your attention, likes, comments and forwarding is my biggest support! Follow my public account “Yubing Yubing” to receive the latest push, which also has some quality resources I share.