HashMap and Set Performance Optimization in Android Kotlin
Article Summary
Using List.contains() instead of Set.contains() in your Android app? You might be making it 900x slower than it needs to be.
Tung Doan breaks down HashMap and Set performance optimization in Android Kotlin with real benchmarks, memory comparisons, and production-ready code examples. This comprehensive guide shows exactly when to use HashMap vs ArrayMap, HashSet vs List, and how to avoid common pitfalls that kill app performance.
Key Takeaways
- HashSet lookups are 900x faster than List.contains() for 10,000 items
- ArrayMap uses 8x less memory than HashMap but slower for datasets over 1,000 items
- Pre-sizing collections eliminates costly resize operations during growth
- Poor hash functions degrade HashMap from O(1) to O(n) performance
- Multi-level indexing in RecyclerView adapters eliminates O(n) searches
Switching from List to HashSet for lookups provides 100-1000x speedup, while choosing ArrayMap for small datasets (<1000 items) cuts memory overhead by 75%.
About This Article
Tung Doan found that a User class with a poor hashCode() implementation, one that returns a constant value of 1, causes all HashMap entries to land in the same bucket. This creates collisions that tank performance from O(1) down to O(n).
Use Objects.hash() to distribute hash values properly across multiple fields. This spreads entries evenly across buckets and takes advantage of Java's built-in hashing algorithm, keeping performance consistent no matter how much data you add.
With a proper hash function, HashMap lookups stay at O(1) average case regardless of dataset size. You avoid the performance drop that happens when collision chains exceed 8 nodes and Java 8+ converts them to trees.