Memory areaseasy0-2 years

A service holds five million numbers in a `List<Integer>` and someone proposes switching to `int[]` "to save a bit of overhead." How much memory does that actually save, and why is the answer not obvious from the field types alone?

It's not a small saving — it's roughly four times less memory, because every element in a List<Integer> is a full heap object, not a raw number. Every Java object carries a 12-byte header (an 8-byte mark word plus a 4-byte compressed class pointer) and gets padded to a multiple of 8 bytes, so a boxed Integer — 4 bytes of actual data — costs 16 bytes as an object, plus a 4-byte reference to it sitting in the list's backing array. An int[] of the same five million numbers is just the numbers, packed contiguously with one small array header. The 'overhead' isn't a rounding error on top of the data, it's several times the size of the data itself, and it's invisible from the source code because List<Integer> and int[] look like they hold the same thing.

The lesson behind it →
More on Memory areas