Video in progress

Strong Junior ⚙️ JVM and memory

How much space does an ordinary object take on the heap, and what does it depend on?

In 64-bit HotSpot every object has a 12-byte header (with a compressed class pointer), then the fields follow, and the size is padded to a multiple of 8 bytes. That is why new Object() is 16 bytes and an Integer is also 16 bytes, even though an int is only 4 bytes.

📖 Answer

The structure of an object:

  • the mark word (8 bytes): hash code, GC age, lock state;
  • the class pointer (4 bytes with compressed oops on, otherwise 8);
  • fields: int 4, long 8, a reference 4 (compressed) or 8;
  • padding: so the total size is divisible by 8.

Arrays add another 4 bytes for the length to the header.

Why this matters in practice:

List<Integer> ids = new ArrayList<>();   // 1 million elements
int[] ids2 = new int[1_000_000];         // ~4 MB

In the first variant each element is a separate Integer object (16 bytes) plus a reference in the array (4 bytes): about 20 MB, five times as much, and more work for the GC too.

Compressed oops are turned on automatically when the heap is smaller than 32 GB. That is why -Xmx32g sometimes gives less useful space than -Xmx31g: references switch to 8 bytes.

For exact measurement, don't guess; use the JOL (Java Object Layout) library:

System.out.println(ClassLayout.parseClass(Order.class).toPrintable());

Compact object headers shrink the header to 8 bytes: experimental in JDK 24 (JEP 450), a product feature in JDK 25 (JEP 519), but not the default yet; it is turned on separately with -XX:+UseCompactObjectHeaders.