Skip to lesson

Estimating and measuring object size

An object's size has two meanings. Its shallow size is the bytes of the object itself; its retained size is how much memory would be freed if it were gone. The first is easy to estimate by hand, the second needs you to follow references, and the difference is what decides how big your program really is.

Adding up header, fields and padding by hand

A shallow size estimate is the 12-byte header plus each field's size, rounded up to a multiple of 8. It uses the rules from the previous lesson for 64-bit HotSpot (Java 17 and 21, default settings, heap under 32 GB).

Example 1 · Shallow size of a fee receipt, by hand

FeeReceiptEstimateDemo.javaJava
public class FeeReceiptEstimateDemo {    // class FeeReceipt { long receiptNo; int amountPaise; String studentName; LocalDate paidOn; boolean online; }    public static void main(String[] args) {        String[] names = {"header", "long receiptNo", "int amountPaise", "String studentName",                          "LocalDate paidOn", "boolean online"};        int[] sizes = {12, 8, 4, 4, 4, 1};
        System.out.printf("%-20s %s%n", "Part", "Bytes");        int raw = 0;        for (int i = 0; i < names.length; i++) {            System.out.printf("%-20s %5d%n", names[i], sizes[i]);            raw += sizes[i];        }        int shallow = (raw + 7) / 8 * 8;        System.out.printf("%-20s %5d%n", "sum", raw);        System.out.printf("%-20s %5d%n", "rounded up to 8", shallow);        System.out.println("Not counted: the String and the LocalDate objects themselves");    }}
Output
Part                 Bytes
header                  12
long receiptNo           8
int amountPaise          4
String studentName       4
LocalDate paidOn         4
boolean online           1
sum                     33
rounded up to 8         40
Not counted: the String and the LocalDate objects themselves

What this code does

  • Each reference field (studentName, paidOn) adds only 4 bytes: the pointer. The total of 33 is rounded up to 40.
  • The String and LocalDate objects live elsewhere on the heap. To know the full cost of a receipt you must add them too, which leads to deep and retained size.

A reference field such as String studentName counts as 4 bytes, the size of the pointer. The String it points to is a separate object with its own header and is not part of this number. Write the fields in a column, add them, round up. With practice you can do it in your head for most small classes.

Shallow size versus deep and retained size

Shallow size counts only the object itself. Deep size counts the object plus everything you can reach by following its references.

Example 2 · Shallow, deep and retained size of a student

ShallowDeepRetainedDemo.javaJava
import java.util.ArrayList;import java.util.Arrays;import java.util.HashSet;import java.util.List;import java.util.Set;
class Box {    final String name;    final int size;    final List<Box> refs = new ArrayList<>();
    Box(String name, int size) {        this.name = name;        this.size = size;    }
    Box pointsTo(Box... others) {        refs.addAll(Arrays.asList(others));        return this;    }}
public class ShallowDeepRetainedDemo {    // Collect every box reachable from 'from', never passing through 'skip'.    static void reach(Box from, Box skip, Set<Box> seen) {        if (from == skip || !seen.add(from)) {            return;        }        for (Box r : from.refs) {            reach(r, skip, seen);        }    }
    static int bytes(Set<Box> boxes) {        int total = 0;        for (Box b : boxes) {            total += b.size;        }        return total;    }
    public static void main(String[] args) {        // Sizes are 64-bit HotSpot estimates (Java 17 and 21, defaults).        Box college = new Box("String IIT Madras", 24).pointsTo(new Box("byte[10]", 32));        Box nameA = new Box("String Aarav", 24).pointsTo(new Box("byte[5]", 24));        Box nameB = new Box("String Diya", 24).pointsTo(new Box("byte[4]", 24));        Box aarav = new Box("Student Aarav", 24).pointsTo(nameA, college);        Box diya = new Box("Student Diya", 24).pointsTo(nameB, college);        List<Box> roots = List.of(aarav, diya);   // what the program still uses
        Set<Box> deep = new HashSet<>();        reach(aarav, null, deep);
        Set<Box> all = new HashSet<>();        Set<Box> withoutAarav = new HashSet<>();        for (Box root : roots) {            reach(root, null, all);            reach(root, aarav, withoutAarav);        }
        System.out.println("Shallow size of Aarav:  " + aarav.size + " bytes");        System.out.println("Deep size of Aarav:     " + bytes(deep) + " bytes (" + deep.size() + " objects)");        System.out.println("Retained size of Aarav: " + (bytes(all) - bytes(withoutAarav)) + " bytes");    }}
Output
Shallow size of Aarav:  24 bytes
Deep size of Aarav:     128 bytes (5 objects)
Retained size of Aarav: 72 bytes

What this code does

  • Box is a tiny model of heap objects with estimated sizes. Aarav's deep size adds his name string, its letters, the college string and its letters: 24 + 24 + 24 + 24 + 32 = 128.
  • Retained size is "all reachable bytes" minus "bytes still reachable if Aarav were gone". Diya still points to the college string, so only Aarav, his name and its letters are freed: 72 bytes.
  • The seen set makes each object count once, even when it is reached twice.

Retained size counts the object plus only those objects that nothing else keeps alive: the memory the GC could free if this one object became unreachable. The three differ when objects are shared. If two students point to the same college name String, that string is in both students' deep size but in neither one's retained size, because removing one student does not free it.

Retained size is the one that matters for leaks. Heap dump tools such as Eclipse MAT and VisualVM show it next to the shallow size; the Diagnosing Memory Problems module uses them.

When counting deep size, count each shared object once. Walking references without remembering what you have seen counts shared objects twice, and a cycle would never end.

Seeing real layouts with JOL

JOL (Java Object Layout) is a small OpenJDK tool that prints how the running JVM actually lays out an object: each field's offset and size, the header, the padding, and the total.

Java
// Needs the JOL library (org.openjdk.jol:jol-core), not part of the JDKimport org.openjdk.jol.info.ClassLayout;import org.openjdk.jol.info.GraphLayout;import org.openjdk.jol.vm.VM;
// inside a method:System.out.println(VM.current().details());                              // header and reference sizesSystem.out.println(ClassLayout.parseClass(Student.class).toPrintable()); // offsets, sizes, paddingSystem.out.println(GraphLayout.parseInstance(student).totalSize());      // deep size in bytes

It is a separate library (org.openjdk.jol:jol-core on Maven Central), not part of the JDK. ClassLayout shows the shallow layout of one class; GraphLayout walks references and gives the deep size of an object graph. Because it asks the running JVM, it shows the truth for your exact JDK and flags, including changes such as -Xmx40g.

  • Without a library, jcmd <pid> GC.class_histogram (previous lesson) gives real per-class sizes: bytes ÷ instances.
  • java.lang.instrument.Instrumentation.getObjectSize(obj) gives a shallow size, but only inside a Java agent.

Rough measurement with Runtime.totalMemory and freeMemory

Runtime.totalMemory() - Runtime.freeMemory() is the heap the JVM is using right now, in bytes. Read it before and after creating many objects, divide the growth by the count, and you get a rough size per object.

Example 3 · A rough size per object with Runtime

RuntimeMeasureDemo.javaJava
class Point {    int x;    int y;
    Point(int x, int y) {        this.x = x;        this.y = y;    }}
public class RuntimeMeasureDemo {    static long usedBytes() {        Runtime rt = Runtime.getRuntime();        return rt.totalMemory() - rt.freeMemory();    }
    static long usedAfterGc() {        System.gc();          // only a request: the JVM may skip it        return usedBytes();    }
    public static void main(String[] args) {        int n = 1_000_000;        long before = usedAfterGc();
        Point[] points = new Point[n];        for (int i = 0; i < n; i++) {            points[i] = new Point(i, i);        }
        long after = usedAfterGc();        long grew = after - before;        System.out.println("Heap used before: " + before / 1024 + " KB");        System.out.println("Heap used after:  " + after / 1024 + " KB");        System.out.println("Grew by " + grew / 1024 + " KB for " + n + " points");        System.out.println("About " + grew / n + " bytes per point (object + array slot)");        System.out.println("Last point x = " + points[n - 1].x);   // keeps the array in use    }}
Sample output
Heap used before: 1432 KB
Heap used after:  28105 KB
Grew by 26672 KB for 1000000 points
About 27 bytes per point (object + array slot)
Last point x = 999999

What this code does

  • Each point should cost about 28 bytes: 24 for the Point object and 4 for its slot in the Point[] array. This run showed 27, a little less: objects left over from JVM start-up were freed between the two readings, which hides part of the growth.
  • The last line uses the array after the second reading, so it is still reachable when the memory is measured. Your numbers will differ.

Example 4 · Shallow size hides what a list holds

ListDeepSizeDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class ListDeepSizeDemo {    static long usedAfterGc() {        System.gc();          // a request, not a promise        Runtime rt = Runtime.getRuntime();        return rt.totalMemory() - rt.freeMemory();    }
    public static void main(String[] args) {        int n = 100_000;        long before = usedAfterGc();
        List<String> rollNumbers = new ArrayList<>();        for (int i = 1; i <= n; i++) {            rollNumbers.add(String.format("CS2024-%06d", i));   // e.g. CS2024-000001        }
        long after = usedAfterGc();        long grew = after - before;        System.out.println("Shallow size of the ArrayList: about 24 bytes");        System.out.println("Measured growth: " + grew / 1024 + " KB");        System.out.println("About " + grew / n + " bytes per roll number");        System.out.println("First: " + rollNumbers.get(0) + ", last: " + rollNumbers.get(n - 1));    }}
Sample output
Shallow size of the ArrayList: about 24 bytes
Measured growth: 5433 KB
About 55 bytes per roll number
First: CS2024-000001, last: CS2024-100000

What this code does

  • The ArrayList object itself is about 24 bytes, yet the heap grew by about 5.3 MB for 100,000 roll numbers.
  • By estimate each entry costs about 60 bytes: a 24-byte String, a 32-byte byte[] for its 13 letters and a 4-byte slot in the list's array. This run measured 55 and another run 60, which shows how rough Runtime readings are.

It is rough for three reasons: garbage from earlier work is counted until the GC runs, System.gc() is only a request, and other threads (including the JVM's own) allocate at the same time. Create many objects (thousands, not one), keep them reachable until the second reading, and repeat the run.

Use this for quick checks only. For real numbers use a class histogram, JOL, or a heap dump.

Next step

Check your understanding

12 quick questions