Android中使用SparseArray替代HashMap提高性能

一、介紹

SparseArray是 Android框架獨有的類,在標準的JDK中不存在這個類。它要比 HashMap 節省內存,某些情況下比HashMap性能更好,按照官方問答的解釋,主要是因爲SparseArray不需要對key和value進行auto- boxing(將原始類型封裝爲對象類型,比如把int類型封裝成Integer類型),結構比HashMap簡單(SparseArray內部主要使用 兩個一維數組來保存數據,一個用來存key,一個用來存value)不需要額外的額外的數據結構(主要是針對HashMap中的HashMapEntry 而言的)。

單純從字面上來理解,SparseArray指的是稀疏數組(Sparse array),所謂稀疏數組就是數組中大部分的內容值都未被使用(或都爲零),在數組中僅有少部分的空間使用。因此造成內存空間的浪費,爲了節省內存空間,並且不影響數組中原有的內容值,我們可以採用一種壓縮的方式來表示稀疏數組的內容。

文中關於稀疏數組(Sparse array)的定義說明參照至:

http://hi.baidu.com/piaopiao_0423/item/d8cc2b99729f8380581461d1

二、使用

SparseArray<String> sparseArray=new SparseArray<String>();  
 
//增加  兩種方式  
sparseArray.append(0, "This is 0");  
sparseArray.append(1, "This is 1");  
sparseArray.append(2, "This is 2");  

sparseArray.put(3, "This is 3");  
sparseArray.put(4, "This is 4");  

//修改  兩種方式  
sparseArray.put(0, "This is new 0");//在put數據之前,會先查找要put的數據是否已經存在,如果存在就是修改,不存在就添加。
sparseArray.put(1, "This is new 1");  
sparseArray.setValueAt(2, "This is new 2");  
sparseArray.setValueAt(3, "This is new 3");  

//刪除  四種方式
sparseArray.delete(0);  
sparseArray.remove(0); //直接調用的delete(int key)
sparseArray.removeAt(0); 
sparseArray.clear(); 

//查找數據
sparseArray.get(0);//當找不到的時候,默認返回null
sparseArray.get(0, "找不到的默認值");

//遍歷, 注意:  
//在執行刪除後sparseArray的size()是變化的,因此在遍歷前,先求值。
for (int i = 0,j=sparseArray.size(); i < j; i++) {  
System.out.println("遍歷得到位置"+i+"的值爲:"+sparseArray.get(i));  
} 

//查找某個位置的鍵  ,注意:查看鍵所在位置,由於是採用二分法查找鍵的位置,所以找不到時返回小於0的數值,而不是返回-1。返回的負值是表示它在找不到時所在的位置。
int key =sparseArray.keyAt(1);  
System.out.println("查找位置1處的鍵 key="+key);  

//查找某個位置的值  
String value=(String) sparseArray.valueAt(1);  
System.out.println("查找位置1處的值 value="+value); 

//查看值所在位置,沒有的話返回-1:
int index =sparseArray.indexOfValue("aa");

三. 其它

1.  在正序插入數據時候,SparseArray比HashMap要快一些;HashMap不管是倒序還是正序開銷幾乎是一樣的;但是SparseArray的倒序插入要比正序插入要慢10倍以上。(因爲SparseArray在檢索數據的時候使用的是二分查找,所以每次插入新數據的時候SparseArray都需要重新排序,所以代碼4中,逆序是最差情況。

2. 相應的也有SparseBooleanArray,用來取代HashMap<Integer, Boolean>,SparseIntArray用來取代HashMap<Integer, Integer>,用法基本類似。

四、可序列化的擴展

地址:http://stackoverflow.com/questions/14899718/how-to-store-sparsearray-in-bundle

public class SerializableSparseArray<E> extends SparseArray<E> implements Serializable{

    private static final long serialVersionUID = 824056059663678000L;

    public SerializableSparseArray(int capacity){
        super(capacity);
    }

    public SerializableSparseArray(){
        super();
    }

    /**
     * This method is private but it is called using reflection by java
     * serialization mechanism. It overwrites the default object serialization.
     *
     * <br/><br/><b>IMPORTANT</b>
     * The access modifier for this method MUST be set to <b>private</b> otherwise {@link java.io.StreamCorruptedException}
     * will be thrown.
     *
     * @param oos
     *            the stream the data is stored into
     * @throws IOException
     *             an exception that might occur during data storing
     */
    private void writeObject(ObjectOutputStream oos) throws IOException {
        Object[] data = new  Object[size()];

        for (int i=data.length-1;i>=0;i--){
            Object[] pair = {keyAt(i),valueAt(i)}; 
            data[i] = pair;
        }
        oos.writeObject(data);
    }

    /**
     * This method is private but it is called using reflection by java
     * serialization mechanism. It overwrites the default object serialization.
     *
     * <br/><br/><b>IMPORTANT</b>
     * The access modifier for this method MUST be set to <b>private</b> otherwise {@link java.io.StreamCorruptedException}
     * will be thrown.
     *
     * @param oos
     *            the stream the data is read from
     * @throws IOException
     *             an exception that might occur during data reading
     * @throws ClassNotFoundException
     *             this exception will be raised when a class is read that is
     *             not known to the current ClassLoader
     */
    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
        Object[] data = (Object[]) ois.readObject();
        for (int i=data.length-1;i>=0;i--){
            Object[] pair = (Object[]) data[i]; 
            this.append((Integer)pair[0],(E)pair[1]);
        }
        return;
    }


}


參考:

http://liuzhichao.com/p/832.html

http://www.open-open.com/lib/view/open1402906434918.html

發佈了86 篇原創文章 · 獲贊 12 · 訪問量 42萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章