Bundle vs HashMap in Android: Memory Efficiency and Performance
In Android, Bundles backed by memory‑efficient ArrayMap use binary search and shrinkable storage, making them far smaller and faster to transmit than HashMaps, whose fixed‑size growth and lack of shrinkage consume more memory; thus Parcelable Bundles are preferred for IPC, while Serializable remains suited only for persistent storage.
In Android, the Bundle class is internally backed by an ArrayMap, which stores keys and values in two parallel arrays. It uses binary search for look‑ups (O(log n)) but incurs O(n) cost for insertions and deletions because elements must be shifted.
ArrayMap grows by 1.5× when needed and can shrink to 50% of its size when usage falls below one‑third, resulting in lower memory consumption compared with HashMap.
HashMap (Java 1.8) combines an array, linked list, and red‑black tree. Its default capacity is 16 and it doubles when 75% full, without any shrink‑back mechanism, so it typically occupies more memory.
Android activities exchange data via Intents, which rely on the Binder IPC mechanism. The Binder transaction buffer is limited to 1 MB, making large HashMap payloads impractical; Bundle’s compact representation ensures faster transmission and less memory usage.
For serialization, Serializable uses Java’s ObjectInputStream/ObjectOutputStream, heavy reflection, and requires a matching serialVersionUID, leading to high GC overhead. Parcelable implements custom, reflection‑free serialization, offering significantly better performance for in‑memory data transfer.
Consequently, Parcelable (via Bundle) is recommended for passing data between components, while Serializable remains convenient for persisting objects to files or databases.
Java Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.