為什么要用SparseArray來替換HashMap?

博文背景:

在Android 中使用HashMap 的時候看到過提示。

HashMap<Integer,Object> mp = new HashMap<Integer,Object>(); 

提示:Use new SparseArray<Object>(...) instead for better performance意思是,使用 SparseArray 將獲得更好的性能
(注:這個提示我再eclipse 中見過,而在studio 中并沒有看到過這種提示)

查閱網(wǎng)上資料關于SparseArray文檔介紹,分析如下(ps:借鑒網(wǎng)上大佬的翻譯):

SparseArrays map integers to Objects. Unlike a normal array of Objects, there can be gaps in the indices. It is intended to be more memory efficient than using a HashMap to map Integers to Objects, both because it avoids auto-boxing keys and its data structure doesn’t rely on an extra entry object for each mapping.

(譯文+個人理解)
SparseArrays不同于普通的對象數(shù)組。there can be gaps in the indices.(指針中能夠存在空白?注:這句我不太理解,不知道怎樣翻譯,是說SparseArrays 是不連續(xù)存儲?)。它的目的是比使用從整數(shù)映射對象的HashMap(簡單來說就是 HashMap<Integer,Object>)有更有效的使用內存。

同一時候也避免auto-boxing(自己主動裝箱)(注:auto-boxing(自己主動裝箱):將原始類型封裝為對象類型。比方把int類型封裝成Integer類型。)和數(shù)據(jù)結構對每條映射不依賴額外的Entry 對象(注:這里是和HashMap做的對照。在HashMap有須要引入Entry<K,V>,而SparseArrays比較簡單,里面是兩個一維數(shù)組 int[] mKeys; 和 Object[] mValues)

Note that this container keeps its mappings in an array data structure, using a binary search to find keys. The implementation is not intended to be appropriate for data structures that may contain large numbers of items. It is generally slower than a traditional HashMap, since lookups require a binary search and adds and removes require inserting and deleting entries in the array. For containers holding up to hundreds of items, the performance difference is not significant, less than 50%.

注意,這個容器在數(shù)組數(shù)據(jù)結構中維持一個映射關系。使用二分查找法來找到key.它的目標不是為了適應數(shù)據(jù)結構中包括大量數(shù)據(jù)的情況。

通常情況下要比傳統(tǒng)的HashMap慢,由于查找是用二分查找法搜索,加入和刪除須要對數(shù)組進行加入和刪除。

對于有幾百條的數(shù)據(jù)的容器。性能差異不大,不超過50%(注:這里我理解的是, SparseArrays 的優(yōu)勢更體如今小數(shù)量上)

To help with performance, the container includes an optimization when removing keys: instead of compacting its array immediately, it leaves the removed entry marked as deleted. The entry can then be re-used for the same key, or compacted later in a single garbage collection step of all removed entries. This garbage collection will need to be performed at any time the array needs to be grown or the the map size or entry values are retrieved.

為了提高性能,該容器提供了一個優(yōu)化:當刪除key鍵時。不是立刻刪除這一項,而是留下須要刪除的選項給一個刪除的標記。

該條目能夠被又一次用于同樣的key,或者被單個垃圾收集器逐步刪除完所有的條目后壓縮。在不論什么時候。當數(shù)組須要增長(注:這里我理解為 put、append之類的操作)或者Map 的長度、entry的value須要被檢索的時候,該垃圾收集器就會運行(注:這里能夠從代碼中發(fā)現(xiàn)。google在相應的方法中調用 gc() 方法)。

It is possible to iterate over the items in this container using

  • {@link #keyAt(int)} and {@link #valueAt(int)}. Iterating over the keys using
  • keyAt(int) with ascending values of the index will return the
  • keys in ascending order, or the values corresponding to the keys in ascending
  • order in the case of valueAt(int).

在此使用此容器時,能夠迭代遍歷當中的item.. keyAt(int) 返回升序下的key .
valueAt(int) 返回升序狀態(tài)下。key 相應的value值。

與HashMap比較優(yōu)點?

key,value 類型的比較

HashMap | key:隨意類型 | value:隨意類型
SparseArray | key:Integer | value:隨意類型
SparseBooleanArray | key:Integer | value:Boolean類型。
SparseIntArray | key:Integer | value:Integer類型。
LongSparseArray | key:Long | value:隨意類型

依據(jù)需求的不同,找到合適的方法才是上上策。

內部存儲的比較

SparseArray |: int[] mkeys和 Object[] mvalues 來存儲key和value
HashMap | : 內部存儲必須使用Entry<k,v>

其他分析

  • 創(chuàng)建數(shù)據(jù)

以10000條數(shù)據(jù)為例。HashMap用去約13.2M內存,SparseArray共用去 8.626M內存。

  • 數(shù)據(jù)插入

在正序插入數(shù)據(jù)時候,SparseArray比HashMap要快一些;HashMap無論是倒序還是正序開銷差點兒是一樣的。可是SparseArray的倒序插入要比正序插入要慢很多,為什么呢?
原因:SparseArray在檢索數(shù)據(jù)的時候使用的是二分查找,所以每次插入新數(shù)據(jù)的時候SparseArray都須要又一次排序,所以逆序是最差情況。

  • 數(shù)據(jù)檢索

SparseArray中存在須要檢索的下標時。SparseArray的性能略勝一籌可是當檢索的下標比較離散時,SparseArray須要使用多次二分檢索,性能顯然比hash檢索方式要慢一些了。

  • 接口實現(xiàn)

    HashMap實現(xiàn)了Cloneable, Serializable SparseArray 實現(xiàn)了Cloneable 接口,也就是說SparseArray 是不支持序列化的。

  • 運行速度上比較,見大神分析:(傳送門)

源碼就不粘貼了,分析部分代碼:

<pre><code>
/**

  • Adds a mapping from the specified key to the specified value,

  • replacing the previous mapping from the specified key if there

  • was one.
    通過指定的key和value加入一個鍵值對,假設這個位置已經(jīng)存在一個了,則替換掉
    */
    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++;
    

    }
    }

/**

  • Puts a key/value pair into the array, optimizing for the case where
  • the key is greater than all existing keys in the array.
    通過指定的key和value加入一個鍵值對,在原有的基礎上添加
    */
    public void append(int key, E value) {
    if (mSize != 0 && key <= mKeys[mSize - 1]) {
    put(key, value);
    return;
    }
    </code></pre>

僅用于記錄備忘分享,如有版權問題煩請私信!謝謝

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容