Member-only story

Why use SparseArray instead of HashMap

Source code analysis of SparseArray

Beck Moulton
2 min readSep 28, 2024

advantage

  1. 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.
  2. Efficient search Using binary search to locate elements in a key array, the search time complexity is O (log N).
  3. Automatic expansion GrowingArray Utils ensures that arrays automatically expand when needed, reducing the hassle of manually managing array sizes.
  4. Avoid automatic packing :与 HashMap<Integer, Object> 不同,SparseArray 直接使用 int 类型键,避免了自动装箱的开销。

shortcoming

  1. 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.
  2. The key must be an integer Can only be used for integer keys, not universal enough.
  3. 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>

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

No responses yet