ArrayMap源码分析

ArrayMap是Android提供的一种替换HashMap的数据结构,官方对它的介绍说ArrayMap是一种更有效率的Map结构,其原理是内部维护了两个数组,一个数组用来保存每一个key值得hash值,另一个数组用来保存key-value, 用来保存key-value的数组是保存hash值数组大小的两倍,下面这张图很好的展示了ArrayMap原理:

ArrayMap.png

来源HashMap,ArrayMap,SparseArray源码分析及性能对比

成员变量

    private static final int BASE_SIZE = 4;

    private static final int CACHE_SIZE = 10;

    static final int[] EMPTY_IMMUTABLE_INTS = new int[0];

    public static final ArrayMap EMPTY = new ArrayMap<>(-1);

    //缓存相关
    static Object[] mBaseCache;
    static int mBaseCacheSize;
    static Object[] mTwiceBaseCache;
    static int mTwiceBaseCacheSize;

    final boolean mIdentityHashCode;
    int[] mHashes;
    Object[] mArray;
    int mSize;
    //集合操作工具类
    MapCollections<K, V> mCollections;

  • mHashes用来存放key值相对应的hash值
  • mArray用来存放key-value, key值在2n处, value在2n+1处
  • ArrayMap还加入了缓存,mBaseCache用来缓存容量为BASE_SIZE的数组,mTwiceBaseCache用来缓存容量为2 * BASE_SIZE的数组

构造函数

    public ArrayMap() {
        this(0, false);
    }


    public ArrayMap(int capacity) {
        this(capacity, false);
    }

    /** {@hide} */
    public ArrayMap(int capacity, boolean identityHashCode) {
        mIdentityHashCode = identityHashCode;

        if (capacity < 0) {
            mHashes = EMPTY_IMMUTABLE_INTS;
            mArray = EmptyArray.OBJECT;
        } else if (capacity == 0) {
            mHashes = EmptyArray.INT;
            mArray = EmptyArray.OBJECT;
        } else {
            allocArrays(capacity);
        }
        mSize = 0;
    }

    public ArrayMap(ArrayMap<K, V> map) {
        this();
        if (map != null) {
            putAll(map);
        }
    }

一般情况下,在开发中我们主要使用空参构造函数和一个参数的构造函数,不过这两个构造函数都是调用了第三个hide的构造函数, 这个构造函数中主要工作就是分配数组

allocArrays

private void allocArrays(final int size) {
        if (mHashes == EMPTY_IMMUTABLE_INTS) {
            throw new UnsupportedOperationException("ArrayMap is immutable");
        }
        if (size == (BASE_SIZE*2)) {
            synchronized (ArrayMap.class) {
                if (mTwiceBaseCache != null) {
                    final Object[] array = mTwiceBaseCache;
                    mArray = array;
                    mTwiceBaseCache = (Object[])array[0];
                    mHashes = (int[])array[1];
                    array[0] = array[1] = null;
                    mTwiceBaseCacheSize--;
                    if (DEBUG) Log.d(TAG, "Retrieving 2x cache " + mHashes
                            + " now have " + mTwiceBaseCacheSize + " entries");
                    return;
                }
            }
        } else if (size == BASE_SIZE) {
            synchronized (ArrayMap.class) {
                if (mBaseCache != null) {
                    final Object[] array = mBaseCache;
                    mArray = array;
                    mBaseCache = (Object[])array[0];
                    mHashes = (int[])array[1];
                    //将缓存置为null
                    array[0] = array[1] = null;
                    //递减mBaseCacheSize
                    mBaseCacheSize--;
                    if (DEBUG) Log.d(TAG, "Retrieving 1x cache " + mHashes
                            + " now have " + mBaseCacheSize + " entries");
                    return;
                }
            }
        }

        mHashes = new int[size];
        mArray = new Object[size<<1];
    }

从代码中可以看到,如果分配的size恰好等于4或者8, 则ArrayMap会优先在缓存中找,如果有缓存则直接使用缓存的数组,这样就避免了频繁的创建数组带来的内存消耗

方法

1. put

 public V put(K key, V value) {
        final int hash;
        int index;
        //查找key值对应的index,如果找到则为正数,否则为负数,代表了将要被插入的位置
        if (key == null) {
            hash = 0;
            //【1.1】
            index = indexOfNull();
        } else {
            hash = mIdentityHashCode ? System.identityHashCode(key) : key.hashCode();
            index = indexOf(key, hash);
        }
        //已存在key值,直接覆盖为新值
        if (index >= 0) {
            index = (index<<1) + 1;
            final V old = (V)mArray[index];
            mArray[index] = value;
            return old;
        }

        //key值并不存在,则对index取反,获取将要被插入的index
        index = ~index;
        if (mSize >= mHashes.length) {
            //确定扩容的容量
            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;
            //重新分配数组,如果满足缓存条件,使用缓存
            allocArrays(n);

            //迁移数组
            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);
            }

            //释放之前的数组,如果之前的数组满足缓存条件,则将数组缓存起来, 【1.2】
            freeArrays(ohashes, oarray, mSize);
        }
        
        //插入数据
        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);
        }

        mHashes[index] = hash;
        mArray[index<<1] = key;
        mArray[(index<<1)+1] = value;
        mSize++;
        return null;
    }

  1. 查找key值对应的index, 这里使用的也是二分搜索法,如果key值已存在则index为正数,否则为负数
  2. 如果key值已存在,直接覆盖为新值
  3. 如果key值不存在,对index取反
  4. 如果容量不够,进行扩容操作,生成新的数组,如果满足缓存条件,还会将就数组缓存起来避免频繁分配数组,之后前移现有数据到新数组
  5. 插入数据

1.1 indexOfNull

    int indexOfNull() {
        final int N = mSize;

        //如果数组为空,那么什么也不做
        if (N == 0) {
            return ~0;
        }
        
        //二分搜索
        int index = ContainerHelpers.binarySearch(mHashes, N, 0);

        //index < 0 代表数组中并不存在key,直接返回
        if (index < 0) {
            return index;
        }

        //如果index处对应的key值恰好就是null, 则直接返回index
        if (null == mArray[index<<1]) {
            return index;
        }

        //从index后面找寻是否存在key为null
        int end;
        for (end = index + 1; end < N && mHashes[end] == 0; end++) {
            if (null == mArray[end << 1]) return end;
        }

        //从index前面找寻是否存在key为null
        for (int i = index - 1; i >= 0 && mHashes[i] == 0; i--) {
            if (null == mArray[i << 1]) return i;
        }
        
        //都没找到,返回将要被插入的索引位置的负数
        return ~end;
    }

indexOf的实现与indexOfNull基本一样,只不过indexOfNull是判断key值是否等于null

1.2 freeArrays

    private static void freeArrays(final int[] hashes, final Object[] array, final int size) {
        if (hashes.length == (BASE_SIZE*2)) {
            synchronized (ArrayMap.class) {
                if (mTwiceBaseCacheSize < CACHE_SIZE) {
                    array[0] = mTwiceBaseCache;
                    array[1] = hashes;
                    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) {
                    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");
                }
            }
        }
    } 
 

CACHE_SIZE等于10,这意味着最多缓存十个数组,当旧的数组大小等于4或者8的时候,都会被缓存

2. get


    public V get(Object key) {
        final int index = indexOfKey(key);
        return index >= 0 ? (V)mArray[(index<<1)+1] : null;
    }

get方法非常简单,获取索引,根据索引返回对应值,就这么简单!

3. remove

    public V remove(Object key) {
        final int index = indexOfKey(key);
        if (index >= 0) {
            return removeAt(index);
        }

        return null;
    }
    
    public V removeAt(int index) {
        final Object old = mArray[(index << 1) + 1];
        if (mSize <= 1) {
            freeArrays(mHashes, mArray, mSize);
            mHashes = EmptyArray.INT;
            mArray = EmptyArray.OBJECT;
            mSize = 0;
        } else {
            //如果容量不到1/3降低ArrayMap容量
            if (mHashes.length > (BASE_SIZE*2) && mSize < mHashes.length/3) {
                //保证容量不小于BASE_SIZE * 2
                final int n = mSize > (BASE_SIZE*2) ? (mSize + (mSize>>1)) : (BASE_SIZE*2);
                final int[] ohashes = mHashes;
                final Object[] oarray = mArray;
                allocArrays(n);

                mSize--;
                if (index > 0) {
                    System.arraycopy(ohashes, 0, mHashes, 0, index);
                    System.arraycopy(oarray, 0, mArray, 0, index << 1);
                }
                if (index < mSize) {
                    System.arraycopy(ohashes, index + 1, mHashes, index, mSize - index);
                    System.arraycopy(oarray, (index + 1) << 1, mArray, index << 1,
                            (mSize - index) << 1);
                }
            } else {
                mSize--;
                if (index < mSize) {
                    //把后面的数据往前前移一位
                    System.arraycopy(mHashes, index + 1, mHashes, index, mSize - index);
                    System.arraycopy(mArray, (index + 1) << 1, mArray, index << 1,
                            (mSize - index) << 1);
                }
                mArray[mSize << 1] = null;
                mArray[(mSize << 1) + 1] = null;
            }
        }
        return (V)old;
    }

remove首先获取索引值,然后直接调用removeAt来删除对应的值,

性能分析

ArrayMap在确定index时,使用的也是二分查找法,其效率肯定会随着数据量的增大而受到影响,另外从代码中也可以看到,ArrayMap中比较频繁的出现了数组迁移,这就又会造成一些性能的损失,但是如果从内存角度来看,ArrayMap内部使用了缓存,且在删除元素后,会适当的缩小容量,减少内存占用,综合来看,如果数据量不大,且鲨如何删除操作不频繁时ArrayMap还是比较适用

推荐阅读更多精彩内容