Java.Collections.Estimate the amount of memory required to store one byte primitive in ArrayList?

let’s estimate how much memory is used to store one byte primitive in an ArrayList<Byte>.


🔥 Spoiler: storing a single byte in an ArrayList<Byte> costs way more than 1 byte — closer to 24–32 bytes per element.

Let’s break it down:


✅ 1. What happens when you do:

ArrayList<Byte> list = new ArrayList<>();
list.add((byte) 42);

You’re actually:

  • Boxing the byte into a Byte object
  • Storing a reference to that Byte in an internal array

🔧 Memory components per element:

📦 A. Byte object (the wrapper)

  • Object header: ~12 bytes
  • Data (byte field): 1 byte
  • Padding: ~3 bytes (to align to 8 bytes)

➕ Total for Byte: ~16 bytes

📦 B. Reference in ArrayList array

  • 1 reference = 4 bytes (on 32-bit) or 8 bytes (on 64-bit with compressed oops)

➕ Reference: ~4–8 bytes


📊 Estimated total memory per byte:

ComponentSize
Byte object~16 bytes
Reference in array~4–8 bytes
Total~20–24 bytes per byte stored

🧠 Comparison with byte[]:

byte[] arr = new byte[1_000_000];
  • Stores raw primitive bytes
  • Total memory: ~1,000,016 bytes (1MB + small overhead)

vs.

ArrayList<Byte> list = new ArrayList<>();
for (int i = 0; i < 1_000_000; i++) {
    list.add((byte)i);
}
  • Memory usage: ~20–24 MB 😱

📌 Summary:

StructureMemory per byteComment
byte[]✅ ~1 byteMost efficient
ArrayList<Byte>❌ ~20–24 bytesDue to boxing + references
LinkedList<Byte>❌❌ ~40–50 bytesExtra overhead from nodes
This entry was posted in Без рубрики. Bookmark the permalink.