Video in progress
In heap analysis, how does shallow size differ from retained size?
Shallow size is the bytes the object itself occupies (header and fields). Retained size is the total memory the GC would free if this object disappeared, that is, all the objects reachable only through it.
📖 Answer
An example: a HashMap object itself is about 48 bytes. That is its shallow size. But it holds the table array inside, thousands of Nodes, and the keys and values. If nobody else holds them, the retained size can be 500 MB.
UserCache (shallow 24 B, retained 512 MB)
└─ HashMap (shallow 48 B)
└─ Node[] (shallow 1 MB)
└─ 200 000 × User + byte[] ...
Why retained matters more: when you hunt for a memory problem, you care about "what is holding the heap". If you sort by shallow size, byte[] and char[] are always at the top, which tells you nothing, because almost everything has a string inside.
One subtle point: if an object is referenced from two places, it doesn't count toward the retained size of either one. It counts toward their common "dominator". That is why sometimes two caches each look small, but together they hold something very large.
The dominator tree is built on exactly this calculation.
Sign up to mark studied questions and save your progress.