Recently listening to colleagues said that the use of Sparsearray instead of HashMap can improve performance, so the edge of the two classes of data structure for a simple analysis.
Data structure of HashMap
HashMap is a combination of arrays and linked lists (in the data structure called "chain-Table hashing"), as shown in:
Photo Source: Java's HashMap and Hashtable
Data structure of Sparsearray
Sparsearray refers to a sparse array (Sparse array), in order to save memory space, and does not affect the value of the contents of the array. Inside there are two key members, Mkeys and Mvalues, each 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++; }
Thus, Sparsearray is a class written specifically for the hashmap of <Interger,Object> in Android, and its core is the binary lookup function (binarysearch), which can speed up the search efficiency, However, when data is inserted or deleted, the efficiency is not high. Memory efficiency should be similar to HashMap, can not be intuitively judged good or bad, need to discuss the situation.
Data structures for HashMap and Sparsearray in Java