Member-only story
Why use SparseArray instead of HashMap
Source code analysis of SparseArray
2 min readSep 28, 2024
advantage
- High memory efficiency SparseArray uses parallel arrays to avoid memory overhead caused by object encapsulation in HashMaps, making it particularly suitable for situations where keys are integers.
- Efficient search Using binary search to locate elements in a key array, the search time complexity is O (log N).
- Automatic expansion GrowingArray Utils ensures that arrays automatically expand when needed, reducing the hassle of manually managing array sizes.
- Avoid automatic packing :与 HashMap<Integer, Object> 不同,SparseArray 直接使用 int 类型键,避免了自动装箱的开销。
shortcoming
- Not suitable for frequent deletion operations The deletion operation only marks the value as’ deleted ‘and requires additional garbage collection steps, which may affect performance.
- The key must be an integer Can only be used for integer keys, not universal enough.
- Fixed capacity expansion Array expansion is performed according to a fixed strategy (expansion by multiples of the current size), which may result in unnecessary memory waste in some extreme cases.
Usage scenarios
Here is an example in a practical application scenario for storing and searching user session data:
public class SessionManager {
private SparseArray<Session>…