Let’s estimate how much memory is needed to store a single byte
primitive in a Java LinkedList<Byte>
.
Even though it’s “just a byte” (which is 1 byte!), the actual memory cost in a LinkedList<Byte>
is much higher because of:
- Boxing (
byte
→Byte
) - Object overhead
- LinkedList node overhead
📦 Breakdown of memory usage per element:
🧱 1. Byte
object (wrapper for byte
)
- Object header: ~12 bytes (with compressed oops)
byte
field: 1 byte- Padding: 3–4 bytes (to align to 8 bytes)
✅ Total for
Byte
object: ~16 bytes
🔗 2. Node<Byte>
in LinkedList
Each node holds:
- A reference to the
Byte
object → 4–8 bytes - A reference to the previous node → 4–8 bytes
- A reference to the next node → 4–8 bytes
- Object header: ~12 bytes
- Padding: to align
✅ Total for
Node
: ~24–32 bytes
➕ Combined total per byte
in LinkedList<Byte>
:
Component | Approx Memory |
---|---|
Byte object | ~16 bytes |
Node overhead | ~24–32 bytes |
Total | ~40–48 bytes per byte 😱 |
So storing 1 million bytes in a LinkedList<Byte>
may use 40–50 MB of memory instead of just 1 MB.
✅ Compare with byte[]
:
byte[]
stores bytes directly, no boxing, no nodes.- 1 byte per element + 12 bytes header + small padding
- Much more efficient: ~1 MB for 1 million bytes.
🧠 Summary:
Structure | Memory per byte | Suitable For |
---|---|---|
LinkedList<Byte> | ❌ ~40–48 bytes | Not memory-efficient |
ArrayList<Byte> | ❌ ~16–24 bytes | Slightly better, still boxed |
byte[] | ✅ 1 byte | Best for raw data |