Data Structure of HashMap and SparseArray in Java
Recently, I heard from my colleagues that replacing HashMap with SparseArray can improve the performance, so we can perform a simple analysis on the data structures of these two classes.
Data Structure of Hashmap
Hashmap is a combination of arrays and linked lists (called "linked list hash" in the data structure), as shown in:
Image Source: Java HashMap and HashTable
SparseArray Data Structure
SparseArray refers to a Sparse array (Sparse array). To save memory space, it does not affect the original content values in the array. There are two key members, mKeys and mValues, both of which are arrays, as shown below:
View its put (int key, E value), as follows:
public void put(int key, E value) { int i = ContainerHelpers.binarySearch(mKeys, mSize, key); if (i >= 0) { mValues[i] = value; } else { i = ~i; if (i < mSize && mValues[i] == DELETED) { mKeys[i] = key; mValues[i] = value; return; } if (mGarbage && mSize >= mKeys.length) { gc(); // Search again because indices may have changed. i = ~ContainerHelpers.binarySearch(mKeys, mSize, key); } mKeys = GrowingArrayUtils.insert(mKeys, mSize, i, key); mValues = GrowingArrayUtils.insert(mValues, mSize, i, value); mSize++; }
It can be seen that SparseArray is The core of this Hashmap-specific class is the binarySearch function, which can accelerate the search efficiency. However, when data is inserted or deleted, the efficiency is not high. The memory efficiency should be similar to that of HashMap, so it cannot be intuitively determined whether the memory is good or bad. It should be discussed in different situations.