亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb

首頁 > 編程 > Java > 正文

深入分析Android系統中SparseArray的源碼

2019-11-26 15:02:18
字體:
來源:轉載
供稿:網友

前言
昨晚想在Android應用中增加一個int映射到String的字典表,使用HashMap實現的時候,Eclipse給出了一個警告,昨晚項目上線緊張,我直接給忽略了,今天看了一下具體的Eclipse提示如下:

  Use new SparseArray<String> (...) instead for better performance 

這個警告的意思是使用SparseArray來替代,以獲取更好的性能。

源碼
因為SparseArray整體代碼比較簡單,先把源碼展示出來,然后再分析為什么使用SparseArray會比使用HashMap有更好的性能。

   

public class SparseArray<E> implements Cloneable {     private static final Object DELETED = new Object();     private boolean mGarbage = false;        private int[] mKeys;     private Object[] mValues;     private int mSize;        /**      * Creates a new SparseArray containing no mappings.      */     public SparseArray() {       this(10);     }        /**      * Creates a new SparseArray containing no mappings that will not      * require any additional memory allocation to store the specified      * number of mappings. If you supply an initial capacity of 0, the      * sparse array will be initialized with a light-weight representation      * not requiring any additional array allocations.      */     public SparseArray(int initialCapacity) {       if (initialCapacity == 0) {         mKeys = ContainerHelpers.EMPTY_INTS;         mValues = ContainerHelpers.EMPTY_OBJECTS;       } else {         initialCapacity = ArrayUtils.idealIntArraySize(initialCapacity);         mKeys = new int[initialCapacity];         mValues = new Object[initialCapacity];       }       mSize = 0;     }        @Override     @SuppressWarnings("unchecked")     public SparseArray<E> clone() {       SparseArray<E> clone = null;       try {         clone = (SparseArray<E>) super.clone();         clone.mKeys = mKeys.clone();         clone.mValues = mValues.clone();       } catch (CloneNotSupportedException cnse) {         /* ignore */       }       return clone;     }        /**      * Gets the Object mapped from the specified key, or <code>null</code>      * if no such mapping has been made.      */     public E get(int key) {       return get(key, null);     }        /**      * Gets the Object mapped from the specified key, or the specified Object      * if no such mapping has been made.      */     @SuppressWarnings("unchecked")     public E get(int key, E valueIfKeyNotFound) {       int i = ContainerHelpers.binarySearch(mKeys, mSize, key);          if (i < 0 || mValues[i] == DELETED) {         return valueIfKeyNotFound;       } else {         return (E) mValues[i];       }     }        /**      * Removes the mapping from the specified key, if there was any.      */     public void delete(int key) {       int i = ContainerHelpers.binarySearch(mKeys, mSize, key);          if (i >= 0) {         if (mValues[i] != DELETED) {           mValues[i] = DELETED;           mGarbage = true;         }       }     }        /**      * Alias for {@link #delete(int)}.      */     public void remove(int key) {       delete(key);     }        /**      * Removes the mapping at the specified index.      */     public void removeAt(int index) {       if (mValues[index] != DELETED) {         mValues[index] = DELETED;         mGarbage = true;       }     }        /**      * Remove a range of mappings as a batch.      *      * @param index Index to begin at      * @param size Number of mappings to remove      */     public void removeAtRange(int index, int size) {       final int end = Math.min(mSize, index + size);       for (int i = index; i < end; i++) {         removeAt(i);       }     }        private void gc() {       // Log.e("SparseArray", "gc start with " + mSize);          int n = mSize;       int o = 0;       int[] keys = mKeys;       Object[] values = mValues;          for (int i = 0; i < n; i++) {         Object val = values[i];            if (val != DELETED) {           if (i != o) {             keys[o] = keys[i];             values[o] = val;             values[i] = null;           }              o++;         }       }          mGarbage = false;       mSize = o;          // Log.e("SparseArray", "gc end with " + mSize);     }        /**      * Adds a mapping from the specified key to the specified value,      * replacing the previous mapping from the specified key if there      * was one.      */     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);         }            if (mSize >= mKeys.length) {           int n = ArrayUtils.idealIntArraySize(mSize + 1);              int[] nkeys = new int[n];           Object[] nvalues = new Object[n];              // Log.e("SparseArray", "grow " + mKeys.length + " to " + n);           System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);           System.arraycopy(mValues, 0, nvalues, 0, mValues.length);              mKeys = nkeys;           mValues = nvalues;         }            if (mSize - i != 0) {           // Log.e("SparseArray", "move " + (mSize - i));           System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i);           System.arraycopy(mValues, i, mValues, i + 1, mSize - i);         }            mKeys[i] = key;         mValues[i] = value;         mSize++;       }     }        /**      * Returns the number of key-value mappings that this SparseArray      * currently stores.      */     public int size() {       if (mGarbage) {         gc();       }          return mSize;     }        /**      * Given an index in the range <code>0...size()-1</code>, returns      * the key from the <code>index</code>th key-value mapping that this      * SparseArray stores.      *      * <p>The keys corresponding to indices in ascending order are guaranteed to      * be in ascending order, e.g., <code>keyAt(0)</code> will return the      * smallest key and <code>keyAt(size()-1)</code> will return the largest      * key.</p>      */     public int keyAt(int index) {       if (mGarbage) {         gc();       }          return mKeys[index];     }        /**      * Given an index in the range <code>0...size()-1</code>, returns      * the value from the <code>index</code>th key-value mapping that this      * SparseArray stores.      *      * <p>The values corresponding to indices in ascending order are guaranteed      * to be associated with keys in ascending order, e.g.,      * <code>valueAt(0)</code> will return the value associated with the      * smallest key and <code>valueAt(size()-1)</code> will return the value      * associated with the largest key.</p>      */     @SuppressWarnings("unchecked")     public E valueAt(int index) {       if (mGarbage) {         gc();       }          return (E) mValues[index];     }        /**      * Given an index in the range <code>0...size()-1</code>, sets a new      * value for the <code>index</code>th key-value mapping that this      * SparseArray stores.      */     public void setValueAt(int index, E value) {       if (mGarbage) {         gc();       }          mValues[index] = value;     }        /**      * Returns the index for which {@link #keyAt} would return the      * specified key, or a negative number if the specified      * key is not mapped.      */     public int indexOfKey(int key) {       if (mGarbage) {         gc();       }          return ContainerHelpers.binarySearch(mKeys, mSize, key);     }        /**      * Returns an index for which {@link #valueAt} would return the      * specified key, or a negative number if no keys map to the      * specified value.      * <p>Beware that this is a linear search, unlike lookups by key,      * and that multiple keys can map to the same value and this will      * find only one of them.      * <p>Note also that unlike most collections' {@code indexOf} methods,      * this method compares values using {@code ==} rather than {@code equals}.      */     public int indexOfValue(E value) {       if (mGarbage) {         gc();       }          for (int i = 0; i < mSize; i++)         if (mValues[i] == value)           return i;          return -1;     }        /**      * Removes all key-value mappings from this SparseArray.      */     public void clear() {       int n = mSize;       Object[] values = mValues;          for (int i = 0; i < n; i++) {         values[i] = null;       }          mSize = 0;       mGarbage = false;     }        /**      * Puts a key/value pair into the array, optimizing for the case where      * the key is greater than all existing keys in the array.      */     public void append(int key, E value) {       if (mSize != 0 && key <= mKeys[mSize - 1]) {         put(key, value);         return;       }          if (mGarbage && mSize >= mKeys.length) {         gc();       }          int pos = mSize;       if (pos >= mKeys.length) {         int n = ArrayUtils.idealIntArraySize(pos + 1);            int[] nkeys = new int[n];         Object[] nvalues = new Object[n];            // Log.e("SparseArray", "grow " + mKeys.length + " to " + n);         System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);         System.arraycopy(mValues, 0, nvalues, 0, mValues.length);            mKeys = nkeys;         mValues = nvalues;       }          mKeys[pos] = key;       mValues[pos] = value;       mSize = pos + 1;     }        /**      * {@inheritDoc}      *      * <p>This implementation composes a string by iterating over its mappings. If      * this map contains itself as a value, the string "(this Map)"      * will appear in its place.      */     @Override     public String toString() {       if (size() <= 0) {         return "{}";       }          StringBuilder buffer = new StringBuilder(mSize * 28);       buffer.append('{');       for (int i=0; i<mSize; i++) {         if (i > 0) {           buffer.append(", ");         }         int key = keyAt(i);         buffer.append(key);         buffer.append('=');         Object value = valueAt(i);         if (value != this) {           buffer.append(value);         } else {           buffer.append("(this Map)");         }       }       buffer.append('}');       return buffer.toString();     }   } 


首先,看一下SparseArray的構造函數:

   

 /**    * Creates a new SparseArray containing no mappings.    */   public SparseArray() {     this(10);   }      /**    * Creates a new SparseArray containing no mappings that will not    * require any additional memory allocation to store the specified    * number of mappings. If you supply an initial capacity of 0, the    * sparse array will be initialized with a light-weight representation    * not requiring any additional array allocations.    */   public SparseArray(int initialCapacity) {     if (initialCapacity == 0) {       mKeys = ContainerHelpers.EMPTY_INTS;       mValues = ContainerHelpers.EMPTY_OBJECTS;     } else {       initialCapacity = ArrayUtils.idealIntArraySize(initialCapacity);       mKeys = new int[initialCapacity];       mValues = new Object[initialCapacity];     }     mSize = 0;   } 

從構造方法可以看出,這里也是預先設置了容器的大小,默認大小為10。

再來看一下添加數據操作:

  /**    * Adds a mapping from the specified key to the specified value,    * replacing the previous mapping from the specified key if there    * was one.    */   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);       }          if (mSize >= mKeys.length) {         int n = ArrayUtils.idealIntArraySize(mSize + 1);            int[] nkeys = new int[n];         Object[] nvalues = new Object[n];            // Log.e("SparseArray", "grow " + mKeys.length + " to " + n);         System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);         System.arraycopy(mValues, 0, nvalues, 0, mValues.length);            mKeys = nkeys;         mValues = nvalues;       }          if (mSize - i != 0) {         // Log.e("SparseArray", "move " + (mSize - i));         System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i);         System.arraycopy(mValues, i, mValues, i + 1, mSize - i);       }          mKeys[i] = key;       mValues[i] = value;       mSize++;     }   } 


再看查數據的方法:

  /**    * Gets the Object mapped from the specified key, or <code>null</code>    * if no such mapping has been made.    */   public E get(int key) {     return get(key, null);   }      /**    * Gets the Object mapped from the specified key, or the specified Object    * if no such mapping has been made.    */   @SuppressWarnings("unchecked")   public E get(int key, E valueIfKeyNotFound) {     int i = ContainerHelpers.binarySearch(mKeys, mSize, key);        if (i < 0 || mValues[i] == DELETED) {       return valueIfKeyNotFound;     } else {       return (E) mValues[i];     }   } 


可以看到,在put數據和get數據的過程中,都統一調用了一個二分查找算法,其實這也就是SparseArray能夠提升效率的核心。

   

 static int binarySearch(int[] array, int size, int value) {     int lo = 0;     int hi = size - 1;        while (lo <= hi) {       final int mid = (lo + hi) >>> 1;       final int midVal = array[mid];          if (midVal < value) {         lo = mid + 1;       } else if (midVal > value) {         hi = mid - 1;       } else {         return mid; // value found       }     }     return ~lo; // value not present   } 

個人認為(lo + hi) >>> 1的方法有些怪異,直接用 lo + (hi - lo) / 2更好一些。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb
久久精品国产久精国产思思| 亚洲一区av在线播放| 国产+成+人+亚洲欧洲| 久久久国产精品亚洲一区| 日本免费久久高清视频| 精品露脸国产偷人在视频| 国产精品狼人色视频一区| 亚洲奶大毛多的老太婆| 国产精品www| 欧美黑人巨大精品一区二区| 国产精品欧美日韩| 亚洲欧美一区二区三区四区| 国产精品18久久久久久首页狼| 国产91|九色| 亚洲国产精品久久| 国产成人av在线| 国产第一区电影| 日韩综合中文字幕| 国产一区欧美二区三区| 久久久久久久久91| 日韩中文字幕在线免费观看| 92裸体在线视频网站| 日韩美女中文字幕| 国产亚洲视频中文字幕视频| 欧美一区二区三区免费观看| 国产成人激情视频| 97精品欧美一区二区三区| 91情侣偷在线精品国产| 成人久久一区二区| 欧美老少配视频| 日本精品中文字幕| 91网站在线看| 日韩视频永久免费观看| 国产精品中文字幕在线| 国产亚洲欧洲黄色| 精品国产电影一区| 欧美日韩综合视频| 亚洲精品国偷自产在线99热| 亚洲欧美激情另类校园| 亚洲国产小视频在线观看| 国产精品一二区| 91成人精品网站| **欧美日韩vr在线| 国产精品永久免费视频| 国产视频999| 日韩a**站在线观看| 这里只有精品视频在线| 亚洲理论在线a中文字幕| 成人黄色免费在线观看| 国产女人精品视频| 日韩av男人的天堂| 91在线观看免费网站| 久久久久久国产精品美女| 欧美黑人国产人伦爽爽爽| 日韩电影免费在线观看| 精品成人69xx.xyz| 国产亚洲精品高潮| 亚洲国产精品资源| 欧美成年人视频网站| 日韩欧美在线一区| 亚洲aⅴ男人的天堂在线观看| 亚洲欧美在线播放| 精品国偷自产在线视频| 国模gogo一区二区大胆私拍| 国产精品扒开腿爽爽爽视频| 国产精品美女av| 久久网福利资源网站| 国产在线播放不卡| 久久久久久尹人网香蕉| 国产99久久精品一区二区 夜夜躁日日躁| 欧美亚洲在线视频| 2019av中文字幕| 日本免费久久高清视频| 久久久999精品| 少妇av一区二区三区| 清纯唯美日韩制服另类| 夜夜躁日日躁狠狠久久88av| 国内精品久久影院| 欧美最近摘花xxxx摘花| 久久久亚洲福利精品午夜| 国产在线精品一区免费香蕉| 91在线视频成人| 久久大大胆人体| 不用播放器成人网| 国产精品自拍小视频| 国产偷亚洲偷欧美偷精品| 亚洲欧美国产精品va在线观看| 在线观看欧美日韩国产| 91精品视频网站| 亚洲午夜精品视频| 国产在线98福利播放视频| 国产综合香蕉五月婷在线| 欧美国产第二页| 自拍偷拍亚洲精品| 精品一区二区三区四区| 国产成人一区二区三区小说| 一道本无吗dⅴd在线播放一区| 国产91露脸中文字幕在线| 性欧美长视频免费观看不卡| 欧美一级电影久久| 亚洲欧美中文字幕| 中文字幕精品视频| 亚洲精品视频播放| 亚洲黄页视频免费观看| 国产精品第二页| 亚洲美女又黄又爽在线观看| 日韩欧美大尺度| 成人激情视频网| 国产一区二区三区高清在线观看| 久久精品国产成人精品| 九九热在线精品视频| 久久国内精品一国内精品| 7m精品福利视频导航| 亚洲精品国产精品乱码不99按摩| 国产成+人+综合+亚洲欧洲| 中国日韩欧美久久久久久久久| 亚洲专区中文字幕| 国内精品在线一区| 亚洲经典中文字幕| 色综合天天狠天天透天天伊人| 丝袜亚洲另类欧美重口| 国产黑人绿帽在线第一区| 亚洲欧美在线一区| 96精品视频在线| 国产亚洲精品美女久久久| 亚洲精品日韩久久久| 成人国内精品久久久久一区| 奇米一区二区三区四区久久| 欧美激情精品久久久| 日韩精品在线免费| 欧美第一黄网免费网站| www欧美xxxx| 国产成人av在线| 国产精品麻豆va在线播放| 日韩av电影免费观看高清| 亚洲最大成人在线| 欧美成人精品在线视频| 亚洲系列中文字幕| 欧美激情欧美狂野欧美精品| 日本一区二区三区在线播放| 亚洲字幕一区二区| 九九热r在线视频精品| 国产视频久久久久久久| 国产专区欧美专区| 日韩中文字幕在线| 国产精品女人久久久久久| 91视频88av| 国产一区二区三区网站| 欧美专区国产专区| 欧美巨大黑人极品精男| 最新中文字幕亚洲| 4388成人网| 国产一区二区三区在线观看视频| 欧美日韩国产色视频| 日本亚洲欧洲色| 国产精品扒开腿爽爽爽视频| 91美女福利视频高清| 色婷婷av一区二区三区在线观看| 操91在线视频| 欧美国产日韩一区二区| 精品中文字幕在线| 国产精品视频一区二区高潮| 精品人伦一区二区三区蜜桃免费| 在线看日韩欧美|