Skip to lesson

Why boxing in big collections costs memory

Java collections hold objects, never primitives. So a List<Integer> of a million numbers is really a million separate Integer objects plus an array of references to them, and a HashMap<Integer, Integer> adds a node object for every entry. For big numeric data that costs 5 to 10 times the memory of plain arrays.

List<Integer> versus int[] for a million values

Boxing is wrapping a primitive value in an object, such as an int in an Integer. A List<Integer> must box every value, because generics work only with objects.

Example 1 · Measured: int[] versus ArrayList<Integer>

ListVsArrayDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class ListVsArrayDemo {    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 = 1_000_000;
        long before = usedAfterGc();        int[] array = new int[n];        for (int i = 0; i < n; i++) {            array[i] = 1000 + i;        }        long arrayKb = (usedAfterGc() - before) / 1024;
        before = usedAfterGc();        List<Integer> list = new ArrayList<>();        for (int i = 0; i < n; i++) {            list.add(1000 + i);                   // autoboxing: a new Integer each time        }        long listKb = (usedAfterGc() - before) / 1024;
        System.out.println("int[]              about " + arrayKb + " KB");        System.out.println("ArrayList<Integer> about " + listKb + " KB");        System.out.println("Ratio: about " + listKb / arrayKb + " times");        System.out.println(array[n - 1] + " " + list.get(n - 1));   // both still in use    }}
Sample output
int[]              about 3625 KB
ArrayList<Integer> about 20776 KB
Ratio: about 5 times
1000999 1000999

What this code does

  • Estimate: int[] is 16 + 4,000,000 bytes (about 3906 KB). The list is 1,000,000 Integer objects of 16 bytes (about 15,625 KB) plus an Object[] that grew to about 1.2 million slots of 4 bytes (about 4,750 KB).
  • Your numbers will differ slightly; the ratio stays close to 5. The last line uses both structures so they stay reachable while measured.

For a million values (64-bit HotSpot, Java 17 and 21, defaults, values outside the -128 to 127 cache): int[] is one object of about 4 MB. ArrayList<Integer> is a million 16-byte Integer objects (about 16 MB) plus its Object[] of 4-byte references (about 4 MB, more with spare growth slots), so about 20 MB. The extra objects also cost time: the GC must track a million more objects, and every read follows a reference and unboxes. For a few hundred values none of this matters. For hundreds of thousands it does.

Per-entry cost of HashMap: entry, key and value objects

A HashMap entry is a HashMap.Node object holding the key's hash, a key reference, a value reference and a next reference: 12 + 4 + 4 + 4 + 4 = 28, so 32 bytes.

Example 2 · A HashMap of 100,000 marks, held for measuring

MarksMapDemo.javaJava
import java.util.HashMap;import java.util.Map;
public class MarksMapDemo {    public static void main(String[] args) throws Exception {        Map<Integer, Integer> marksByRoll = new HashMap<>();        for (int i = 0; i < 100_000; i++) {            marksByRoll.put(20_000 + i, 300 + i % 200);   // roll number -> marks out of 500        }        System.out.println("Entries: " + marksByRoll.size());        System.out.println("Marks of roll 20007: " + marksByRoll.get(20_007));        System.out.println("In another terminal run: jcmd <pid> GC.class_histogram");        System.out.println("Press Enter to exit.");        System.in.read();        System.out.println("Done. The map still has " + marksByRoll.size() + " entries.");    }}
Output
Entries: 100000
Marks of roll 20007: 307
In another terminal run: jcmd <pid> GC.class_histogram
Press Enter to exit.
Done. The map still has 100000 entries.

What this code does

  • Roll numbers from 20000 and marks from 300 are outside the Integer cache, so every key and every value is its own object.
  • The program waits for Enter so you can run jcmd from a second terminal; the last line uses the map, so it stays reachable until then.

Example 3 · What one HashMap entry really costs

Terminal
jcmd <pid> GC.class_histogram
Sample output
<pid>:
 num     #instances         #bytes  class name (module)
-------------------------------------------------------
   1:        100895        3228640  java.util.HashMap$Node (java.base@21.0.7)
   2:        200262        3204192  java.lang.Integer (java.base@21.0.7)
   3:           218        1069344  [Ljava.util.HashMap$Node; (java.base@21.0.7)
   4:          2650         116536  [B (java.base@21.0.7)
...

What this code does

  • A real run on OpenJDK 21 while Example 2 waited, trimmed. HashMap$Node is 32 bytes each and Integer 16 bytes each (200,000 of them: keys and values). Most of the table bytes are one array of 262,144 slots.
  • Together that is about 7.5 MB for 100,000 entries: about 75 bytes per entry, against 8 bytes of real data. The few hundred extra objects belong to the JDK.

The key and value are separate objects, and the map's table has one 4-byte slot per bucket. For HashMap<Integer, Integer> with values outside the cache, each entry costs about 32 (node) + 16 (key) + 16 (value) + 5 to 10 (table slots, kept at most 75% full) = 70 to 75 bytes. The data itself is two ints, 8 bytes.

That is fine for lookups by key in normal-sized maps. It is a problem when a map holds millions of numeric entries, for example marks by roll number for a whole university.

Primitive-friendly options: arrays, BitSet, IntStream

The JDK has three simple tools for numbers without boxing: primitive arrays, BitSet and IntStream. Pick by what the data looks like.

Example 4 · BitSet for attendance, IntStream for marks

PrimitiveOptionsDemo.javaJava
import java.util.BitSet;import java.util.stream.IntStream;
public class PrimitiveOptionsDemo {    public static void main(String[] args) {        int students = 1_000_000;
        // Attendance for one day: one bit per student        BitSet present = new BitSet(students);        for (int roll = 0; roll < students; roll++) {            if (roll % 10 != 0) {                 // every tenth student is absent                present.set(roll);            }        }        System.out.println("Present: " + present.cardinality() + " of " + students);        System.out.println("Roll 30 present? " + present.get(30) + ", roll 31 present? " + present.get(31));        System.out.println("BitSet uses " + present.size() / 8 / 1024 + " KB of bits");        System.out.println("boolean[] would use about " + students / 1024 + " KB");
        // Marks in an int[], worked on with IntStream: no Integer objects        int[] marks = new int[students];        for (int i = 0; i < students; i++) {            marks[i] = 200 + i % 300;        }        long total = IntStream.of(marks).asLongStream().sum();        long above400 = IntStream.of(marks).filter(m -> m > 400).count();        int best = IntStream.of(marks).max().getAsInt();        System.out.println("Total: " + total + ", above 400: " + above400 + ", best: " + best);        System.out.println("Sum of 1 to 100: " + IntStream.rangeClosed(1, 100).sum());    }}
Output
Present: 900000 of 1000000
Roll 30 present? false, roll 31 present? true
BitSet uses 122 KB of bits
boolean[] would use about 976 KB
Total: 349490000, above 400: 329967, best: 499
Sum of 1 to 100: 5050

What this code does

  • BitSet stores one bit per student; size() reports the bits it has room for, about 122 KB here. cardinality() counts the set bits and get(30) reads one flag.
  • IntStream.of(marks) works straight on the int[]: sum (through asLongStream to avoid overflow), filter and max create no Integer objects.
  • Arrays (int[], long[], double[]): fixed-size numeric data, or data indexed by a small number such as a roll number offset. Use Arrays.sort and Arrays.binarySearch on them.
  • BitSet: yes/no flags, one bit each. A million attendance flags take about 122 KB, against about 976 KB for boolean[].
  • IntStream, LongStream, DoubleStream: sum, count, filter and max over primitives with no Integer objects. list.stream().mapToInt(Integer::intValue) converts a boxed list once.
  • Third-party primitive collections (for example Eclipse Collections or fastutil) offer maps such as int-to-int without boxing, when you truly need a map.

Designing memory-friendly classes

A memory-friendly class keeps its data in primitive fields and shares whatever repeats. When millions of objects of one class are alive at the same time, every field type matters.

Example 5 · A heavy class and a light class for exam results

FriendlyClassDemo.javaJava
// Heavy: every field is an objectclass ResultHeavy {    Long roll;    Double percentage;    String grade;       // 4-byte reference + a 24-byte String + a 24-byte byte[] (own copy per record, e.g. read from a file)    Boolean passed;}
enum Grade { A, B, C, D, F }
// Light: primitives, and a shared enum constant for the gradeclass ResultLight {    int roll;    float percentage;    Grade grade;    boolean passed;}
public class FriendlyClassDemo {    static int align(int bytes) {        return (bytes + 7) / 8 * 8;    }
    public static void main(String[] args) {        int heavyObject = align(12 + 4 + 4 + 4 + 4);        int heavyExtras = 24 + 24 + 24 + 24;        int heavy = heavyObject + heavyExtras;
        int light = align(12 + 4 + 4 + 4 + 1);
        int records = 1_000_000;        System.out.println("ResultHeavy: " + heavyObject + " + " + heavyExtras + " = " + heavy + " bytes per record");        System.out.println("ResultLight: " + light + " bytes per record");        System.out.println("For " + records + " records: " + (long) heavy * records / (1024 * 1024)                + " MB versus " + (long) light * records / (1024 * 1024) + " MB");        System.out.println("Objects per record: 5 versus 1");    }}
Output
ResultHeavy: 32 + 96 = 128 bytes per record
ResultLight: 32 bytes per record
For 1000000 records: 122 MB versus 30 MB
Objects per record: 5 versus 1

What this code does

  • ResultHeavy is 32 bytes itself, but each record also drags a Long, a Double, a String and its byte[]: 128 bytes and 5 objects per result. Boolean costs nothing extra because boxing always returns Boolean.TRUE or Boolean.FALSE.
  • ResultLight holds the same information in 32 bytes and 1 object; the five Grade constants are shared by every record. For a million results that is about 122 MB versus 30 MB.

Use int rather than Integer unless you truly need null, the smallest type that safely fits (byte for a coach number, int paise instead of double rupees for money), and an enum instead of a String for a fixed set of values such as grades or booking status. Give an ArrayList or HashMap its expected size up front to avoid spare slots. For really large data, keep columns in parallel arrays (int[] rolls, int[] marks) instead of one object per row. Measure first: these changes only pay off when there are many objects.

Keep double only where fractions are acceptable; for money, whole paise in an int or long are exact and smaller than a Double object.

Next step

Check your understanding

12 quick questions