let’s estimate how much memory is used to store one byte
primitive in an ArrayList<Byte>
.
🔥 Spoiler: storing a single
byte
in anArrayList<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 aByte
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
:
Component | Size |
---|---|
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:
Structure | Memory per byte | Comment |
---|---|---|
byte[] | ✅ ~1 byte | Most efficient |
ArrayList<Byte> | ❌ ~20–24 bytes | Due to boxing + references |
LinkedList<Byte> | ❌❌ ~40–50 bytes | Extra overhead from nodes |