亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Android ArrayMap源代碼分析

 更新時(shí)間:2016年10月25日 08:50:13   投稿:lqh  
這篇文章主要介紹了Android ArrayMap源代碼分析的相關(guān)資料,需要的朋友可以參考下

      分析源碼之前先來(lái)介紹一下ArrayMap的存儲(chǔ)結(jié)構(gòu),ArrayMap數(shù)據(jù)的存儲(chǔ)不同于HashMap和SparseArray。

 Java提供了HashMap,但是HashMap對(duì)于手機(jī)端而言,對(duì)空間的利用太大,所以Android提供了SparseArray和ArrayMap。二者都是基于二分查找,所以數(shù)據(jù)量大的時(shí)候,最壞效率會(huì)比HashMap慢很多。因此建議數(shù)量在千以內(nèi)比較合適。

 一、SparseArray

  SparseArray對(duì)應(yīng)的key只能是int類型,它不會(huì)對(duì)key進(jìn)行裝箱操作。它使用了兩個(gè)數(shù)組,一個(gè)保存key,一個(gè)保存value。

  SparseArray使用二分查找來(lái)找到key對(duì)應(yīng)的插入位置。所以要保證mKeys數(shù)組有序。

  remove的時(shí)候不會(huì)立刻重新清理刪除掉的數(shù)據(jù),而是將對(duì)一個(gè)的數(shù)據(jù)標(biāo)記為DELETE(一個(gè)Object對(duì)象)。在必要的環(huán)節(jié)調(diào)用gc清理標(biāo)記為DELETE的空間。

 二、ArrayMap

  重點(diǎn)介紹一下ArrayMap。

  首先從ArrayMap的四個(gè)數(shù)組說(shuō)起。mHashes,用于保存key對(duì)應(yīng)的hashCode;mArray,用于保存鍵值對(duì)(key,value),其結(jié)構(gòu)為[key1,value1,key2,value2,key3,value3,......];mBaseCache,緩存,如果ArrayMap的數(shù)據(jù)量從4,增加到8,用該數(shù)組保存之前使用的mHashes和mArray,這樣如果數(shù)據(jù)量再變回4的時(shí)候,可以再次使用之前的數(shù)組,不需要再次申請(qǐng)空間,這樣節(jié)省了一定的時(shí)間;mTwiceBaseCache,與mBaseCache對(duì)應(yīng),不過(guò)觸發(fā)的條件是數(shù)據(jù)量從8增長(zhǎng)到12。

   上面提到的數(shù)據(jù)量有8增長(zhǎng)到12,為什么不是16?這也算是ArrayMap的一個(gè)優(yōu)化的點(diǎn),它不是每次增長(zhǎng)1倍,而是使用了如下方法(mSize+(mSize>>1)),即每次增加1/2。

   有了上面的說(shuō)明,讀懂代碼就容易多了。

  1、很多地方用到的indexOf

    這里使用了二分查找來(lái)查找對(duì)應(yīng)的index

int indexOf(Object key, int hash) {
    final int N = mSize;

    // Important fast case: if nothing is in here, nothing to look for.
    //數(shù)組為空,直接返回
    if (N == 0) {
      return ~0;
    }

    //二分查找,不細(xì)說(shuō)了
    int index = ContainerHelpers.binarySearch(mHashes, N, hash);

    // If the hash code wasn't found, then we have no entry for this key.
    //沒(méi)找到hashCode,返回index,一個(gè)負(fù)數(shù)
    if (index < 0) {
      return index;
    }

    // If the key at the returned index matches, that's what we want.
    //對(duì)比key值,相同則返回index
    if (key.equals(mArray[index<<1])) {
      return index;
    }

    // Search for a matching key after the index.
    //如果返回的index對(duì)應(yīng)的key值,與傳入的key值不等,則可能對(duì)應(yīng)的key在index后面
    int end;
    for (end = index + 1; end < N && mHashes[end] == hash; end++) {
      if (key.equals(mArray[end << 1])) return end;
    }

    // Search for a matching key before the index.
    //接上句,后面沒(méi)有,那一定在前面。
    for (int i = index - 1; i >= 0 && mHashes[i] == hash; i--) {
      if (key.equals(mArray[i << 1])) return i;
    }

    // Key not found -- return negative value indicating where a
    // new entry for this key should go. We use the end of the
    // hash chain to reduce the number of array entries that will
    // need to be copied when inserting.
    //毛都沒(méi)找到,那肯定是沒(méi)有了,返回個(gè)負(fù)數(shù)
    return ~end;
  }

 

  2、看一下put方法

public V put(K key, V value) {
    final int hash;
    int index;
    //key是空,則通過(guò)indexOfNull查找對(duì)應(yīng)的index;如果不為空,通過(guò)indexOf查找對(duì)應(yīng)的index
    if (key == null) {
      hash = 0;
      index = indexOfNull();
    } else {
      hash = key.hashCode();
      index = indexOf(key, hash);
    }
    
    //index大于或等于0,一定是之前put過(guò)相同的key,直接替換對(duì)應(yīng)的value。因?yàn)閙Array中不只保存了value,還保存了key。
    //其結(jié)構(gòu)為[key1,value1,key2,value2,key3,value3,......]
    //所以,需要將index乘2對(duì)應(yīng)key,index乘2再加1對(duì)應(yīng)value
    if (index >= 0) {
      index = (index<<1) + 1;
      final V old = (V)mArray[index];
      mArray[index] = value;
      return old;
    }

    //取正數(shù)
    index = ~index;
    //mSize的大小,即已經(jīng)保存的數(shù)據(jù)量與mHashes的長(zhǎng)度相同了,需要擴(kuò)容啦
    if (mSize >= mHashes.length) {
      //擴(kuò)容后的大小,有以下幾個(gè)檔位,BASE_SIZE(4),BASE_SIZE的2倍(8),mSize+(mSize>>1)(比之前的數(shù)據(jù)量擴(kuò)容1/2)
      final int n = mSize >= (BASE_SIZE*2) ? (mSize+(mSize>>1))
          : (mSize >= BASE_SIZE ? (BASE_SIZE*2) : BASE_SIZE);

      if (DEBUG) Log.d(TAG, "put: grow from " + mHashes.length + " to " + n);

      final int[] ohashes = mHashes;
      final Object[] oarray = mArray;
      //擴(kuò)容方法的實(shí)現(xiàn)
      allocArrays(n);

      //擴(kuò)容后,需要把原來(lái)的數(shù)據(jù)拷貝到新數(shù)組中
      if (mHashes.length > 0) {
        if (DEBUG) Log.d(TAG, "put: copy 0-" + mSize + " to 0");
        System.arraycopy(ohashes, 0, mHashes, 0, ohashes.length);
        System.arraycopy(oarray, 0, mArray, 0, oarray.length);
      }

      //看看被廢棄的數(shù)組是否還有利用價(jià)值
      //如果被廢棄的數(shù)組的數(shù)據(jù)量為4或8,說(shuō)明可能利用價(jià)值,以后用到的時(shí)候可以直接用。
      //如果被廢棄的數(shù)據(jù)量太大,扔了算了,要不太占內(nèi)存。如果浪費(fèi)內(nèi)存了,還費(fèi)這么大勁,加了類干啥。
      freeArrays(ohashes, oarray, mSize);
    }

    //這次put的key對(duì)應(yīng)的hashcode排序沒(méi)有排在最后(index沒(méi)有指示到數(shù)組結(jié)尾),因此需要移動(dòng)index后面的數(shù)據(jù)
    if (index < mSize) {
      if (DEBUG) Log.d(TAG, "put: move " + index + "-" + (mSize-index)
          + " to " + (index+1));
      System.arraycopy(mHashes, index, mHashes, index + 1, mSize - index);
      System.arraycopy(mArray, index << 1, mArray, (index + 1) << 1, (mSize - index) << 1);
    }

    //把數(shù)據(jù)保存到數(shù)組中??吹搅税?,key和value都在mArray中;hashCode放到mHashes
    mHashes[index] = hash;
    mArray[index<<1] = key;
    mArray[(index<<1)+1] = value;
    mSize++;
    return null;
  }

    3、remove方法

  remove方法在某種條件下,會(huì)重新分配內(nèi)存,保證分配給ArrayMap的內(nèi)存在合理區(qū)間,減少對(duì)內(nèi)存的占用。但是從這里也可以看出,Android使用的是用時(shí)間換空間的方式。無(wú)論從任何角度,頻繁的分配回收內(nèi)存一定會(huì)耗費(fèi)時(shí)間的。

  remove最終使用的是removeAt方法,此處只說(shuō)明removeAt

 /**
   * Remove the key/value mapping at the given index.
   * @param index The desired index, must be between 0 and {@link #size()}-1.
   * @return Returns the value that was stored at this index.
   */
  public V removeAt(int index) {
    final Object old = mArray[(index << 1) + 1];
    //如果數(shù)據(jù)量小于等于1,說(shuō)明刪除該元素后,沒(méi)有數(shù)組為空,清空兩個(gè)數(shù)組。
    if (mSize <= 1) {
      // Now empty.
      if (DEBUG) Log.d(TAG, "remove: shrink from " + mHashes.length + " to 0");
      //put中已有說(shuō)明
      freeArrays(mHashes, mArray, mSize);
      mHashes = EmptyArray.INT;
      mArray = EmptyArray.OBJECT;
      mSize = 0;
    } else {
      //如果當(dāng)初申請(qǐng)的數(shù)組最大容納數(shù)據(jù)個(gè)數(shù)大于BASE_SIZE的2倍(8),并且現(xiàn)在存儲(chǔ)的數(shù)據(jù)量只用了申請(qǐng)數(shù)量的1/3,
      //則需要重新分配空間,已減少對(duì)內(nèi)存的占用
      if (mHashes.length > (BASE_SIZE*2) && mSize < mHashes.length/3) {
        // Shrunk enough to reduce size of arrays. We don't allow it to
        // shrink smaller than (BASE_SIZE*2) to avoid flapping between
        // that and BASE_SIZE.
        //新數(shù)組的大小
        final int n = mSize > (BASE_SIZE*2) ? (mSize + (mSize>>1)) : (BASE_SIZE*2);

        if (DEBUG) Log.d(TAG, "remove: shrink from " + mHashes.length + " to " + n);

        final int[] ohashes = mHashes;
        final Object[] oarray = mArray;
        allocArrays(n);

        mSize--;
        //index之前的數(shù)據(jù)拷貝到新數(shù)組中
        if (index > 0) {
          if (DEBUG) Log.d(TAG, "remove: copy from 0-" + index + " to 0");
          System.arraycopy(ohashes, 0, mHashes, 0, index);
          System.arraycopy(oarray, 0, mArray, 0, index << 1);
        }
        //將index之后的數(shù)據(jù)拷貝到新數(shù)組中,和(index>0)的分支結(jié)合,就將index位置的數(shù)據(jù)刪除了
        if (index < mSize) {
          if (DEBUG) Log.d(TAG, "remove: copy from " + (index+1) + "-" + mSize
              + " to " + index);
          System.arraycopy(ohashes, index + 1, mHashes, index, mSize - index);
          System.arraycopy(oarray, (index + 1) << 1, mArray, index << 1,
              (mSize - index) << 1);
        }
      } else {
        mSize--;
        //將index后的數(shù)據(jù)向前移位
        if (index < mSize) {
          if (DEBUG) Log.d(TAG, "remove: move " + (index+1) + "-" + mSize
              + " to " + index);
          System.arraycopy(mHashes, index + 1, mHashes, index, mSize - index);
          System.arraycopy(mArray, (index + 1) << 1, mArray, index << 1,
              (mSize - index) << 1);
        }
        //移位后最后一個(gè)數(shù)據(jù)清空
        mArray[mSize << 1] = null;
        mArray[(mSize << 1) + 1] = null;
      }
    }
    return (V)old;
  }

  4、freeArrays

    put中有說(shuō)明,這里就不進(jìn)行概述了,直接上代碼,印證上面的說(shuō)法。

  private static void freeArrays(final int[] hashes, final Object[] array, final int size) {
    //已經(jīng)廢棄的數(shù)組個(gè)數(shù)為BASE_SIZE的2倍(8),則用mTwiceBaseCache保存廢棄的數(shù)組;
    //如果個(gè)數(shù)為BASE_SIZE(4),則用mBaseCache保存廢棄的數(shù)組
    if (hashes.length == (BASE_SIZE*2)) {
      synchronized (ArrayMap.class) {
        if (mTwiceBaseCacheSize < CACHE_SIZE) {
          //array為剛剛廢棄的數(shù)組,mTwiceBaseCache如果有內(nèi)容,則放入array[0]位置,
          //在allocArrays中會(huì)從array[0]取出,放回mTwiceBaseCache
          array[0] = mTwiceBaseCache;
          //array[1]存放hash數(shù)組。因?yàn)閍rray中每個(gè)元素都是Object對(duì)象,所以每個(gè)元素都可以存放數(shù)組
          array[1] = hashes;
          //清除index為2和之后的數(shù)據(jù)
          for (int i=(size<<1)-1; i>=2; i--) {
            array[i] = null;
          }
          mTwiceBaseCache = array;
          mTwiceBaseCacheSize++;
          if (DEBUG) Log.d(TAG, "Storing 2x cache " + array
              + " now have " + mTwiceBaseCacheSize + " entries");
        }
      }
    } else if (hashes.length == BASE_SIZE) {
      synchronized (ArrayMap.class) {
        if (mBaseCacheSize < CACHE_SIZE) {
          //代碼的注釋可以參考上面,不重復(fù)說(shuō)明了
          array[0] = mBaseCache;
          array[1] = hashes;
          for (int i=(size<<1)-1; i>=2; i--) {
            array[i] = null;
          }
          mBaseCache = array;
          mBaseCacheSize++;
          if (DEBUG) Log.d(TAG, "Storing 1x cache " + array
              + " now have " + mBaseCacheSize + " entries");
        }
      }
    }
  }

  5、allocArrays

    算了,感覺(jué)沒(méi)啥好說(shuō)的,看懂了freeArrays,allocArrays自然就理解了。

    總體來(lái)說(shuō),通過(guò)新數(shù)組的個(gè)數(shù)產(chǎn)生3個(gè)分支,個(gè)數(shù)為BASE_SIZE(4),從mBaseCache取之前廢棄的數(shù)組;BASE_SIZE的2倍(8),從mTwiceBaseCache取之前廢棄的數(shù)組;其他,之前廢棄的數(shù)組沒(méi)有存儲(chǔ),因?yàn)樘馁M(fèi)內(nèi)存,這種情況下,重新分配內(nèi)存。

  6、clear和erase

    clear清空數(shù)組,如果再向數(shù)組中添加元素,需要重新申請(qǐng)空間;erase清除數(shù)組中的數(shù)組,空間還在。

  7、get

    主要的邏輯都在indexOf中了,剩下的代碼不需要分析了,看了的都說(shuō)懂(竊笑)。

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

相關(guān)文章

最新評(píng)論