SparseArray详解,我说SparseArray,你说要!

可能在Android 中使用HashMap 的时候看到过提示。
HashMap<Integer,Bitmap> mp = new HashMap<Integer,Bitmap>();
提示:Use new SparseArray<Bitmap>(...) instead for better performance意思是,使用 SparseArray 将获得更好的性能
(注:这个提示我再eclipse 中见过,而在studio 中并没有看到过这样的提示)
那么SparseArray这个类是干嘛使得,有什么优点,特性呢?
ok,我们从下面几点介绍下SparseArray 这个类。

1.武功秘籍之SparseArray(SparseArray文档介绍)

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不同于普通的对象数组,there can be gaps in the indices.(指针中可以存在空白?注:这句我不太理解,不知道如何翻译,是说SparseArrays 是不连续存储?),它的目的是比使用从整数映射对象的HashMap(简单来说就是 HashMap<Integer,Object>)有更有效的使用内存。同时也避免auto-boxing(自动装箱)(注:auto-boxing(自动装箱):将原始类型封装为对象类型,比如把int类型封装成Integer类型。)和数据结构对每条映射不依赖额外的Entry 对象(注:这里是和HashMap做的对比,在HashMap有需要引入Entry<K,V>,而SparseArrays比较简单,里面是两个一维数组 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%.

注意,这个容器在数组数据结构中维持一个映射关系,使用二分查找法来找到key.它的目标不是为了适应数据结构中包含大量数据的情况。通常情况下要比传统的HashMap慢,因为查找是用二分查找法搜索,添加和删除需要对数组进行添加和删除。对于有几百条的数据的容器,性能差异不大,不超过50%(注:这里我理解的是, SparseArrays 的优势更体现在小数量上)

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.

为了提高性能,该容器提供了一个优化:当删除key键时,不是立马删除这一项,而是留下需要删除的选项给一个删除的标记。该条目可以被重新用于相同的key,或者被单个垃圾收集器逐步删除完全部的条目后压缩。在任何时候,当数组需要增长(注:这里我理解为 put、append之类的操作)或者Map 的长度、entry的value需要被检索的时候,该垃圾收集器就会执行(注:这里可以从代码中发现,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) 返回升序状态下,key 对应的value值。

2.SparseArray,HashMap 不服?SOLO

2.1 key,value 类型的比较

HashMap                   key:任意类型         value:任意类型
SparseArray               key:Integer         value:任意类型 
SparseBooleanArray        key:Integer         value:Boolean类型。    
SparseIntArray            key:Integer         value:Integer类型。    
LongSparseArray           key:Long            value:任意类型

根据需求的不同,找到合适的方法才是上上策。

2.2 内部存储的比较

SparseArray  :int[] mKeys 和 Object[] mValues 来存储 key 和 value 
HashMap      :内部存储需要用到 `Entry<K,V>`

2.3 执行速度比较

这里不打算做代码的介绍了,这篇文章里有比较详细的介绍,这里我只打算总结下。(http://www.open-open.com/lib/view/open1402906434918.html

  1. 创建数据
    以10000条数据为例,HashMap用去约13.2M内存,SparseArray共用去 8.626M内存。

  2. 数据插入
    在正序插入数据时候,SparseArray比HashMap要快一些;HashMap不管是倒序还是正序开销几乎是一样的;但是SparseArray的倒序插入要比正序插入要慢许多,为什么呢?
    原因:SparseArray在检索数据的时候使用的是二分查找,所以每次插入新数据的时候SparseArray都需要重新排序,所以逆序是最差情况。

  3. 数据检索
    SparseArray中存在需要检索的下标时,SparseArray的性能略胜一筹但是当检索的下标比较离散时,SparseArray需要使用多次二分检索,性能显然比hash检索方式要慢一些了。

  4. 接口实现
    HashMap实现了Cloneable, Serializable SparseArray 实现了Cloneable 接口,也就是说SparseArray 是不支持序列化的。

3.代码解析-功法传授(Q增 W删 E改 R查)

先天优越之—>初始技能

 /**
  * Creates a new SparseArray containing no mappings.
  * 创建默认容器大小为10的SparseArray
  */
public SparseArray() {
    this(10);
}

public SparseArray(int initialCapacity) {...}

如虎添翼之 —>

/**
 * 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添加一个键值对,如果这个位置已经存在一个了,则替换掉
 */
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;
    }

    if (mGarbage && mSize >= mKeys.length) {
        gc();
    }

    mKeys = GrowingArrayUtils.append(mKeys, mSize, key);
    mValues = GrowingArrayUtils.append(mValues, mSize, value);
    mSize++;
}

割袍断义之 —>

/**
 * Removes the mapping from the specified key, if there was any.
 * 从键值对中删除指定的key
 */
public void delete(int key) {
    int i = ContainerHelpers.binarySearch(mKeys, mSize, key);

    if (i >= 0) {
        if (mValues[i] != DELETED) {
            mValues[i] = DELETED;
            mGarbage = true;
        }
    }
}

/**
 * @hide
 * 隐藏方法
 * Removes the mapping from the specified key, if there was any, returning the old value.
 * 从键值对中删除指定的key,如果在任何地方还有用到,会返回旧值。
 */
public E removeReturnOld(int key) {
    int i = ContainerHelpers.binarySearch(mKeys, mSize, key);

    if (i >= 0) {
        if (mValues[i] != DELETED) {
            final E old = (E) mValues[i];
            mValues[i] = DELETED;
            mGarbage = true;
            return old;
        }
    }
    return null;
}

/**
 * Alias for {@link #delete(int)}. (注意:这里是调用的delete 的方法,所以remove方法和 delete效果是一样的)
 */
public void remove(int key) {
    delete(key);
}
/**
 * Removes the mapping at the specified index.
 * 删除指定index(注意这里不是删除指定的key,但是其实我们可以发现这个实现是和delete方法是一样的)
 */
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 index  开始删除的位置
 * @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);
    }
}

偷梁换柱之—>

/**
 * Returns the index for which {@link #keyAt} would return the
 * specified key, or a negative number if the specified
 * key is not mapped.
 * 返回key 对应的index,如果指定的key没有找到则返回一个负数
 */
public int indexOfKey(int key) {
    if (mGarbage) {
        gc();
    }

    return ContainerHelpers.binarySearch(mKeys, mSize, key);
}

/**
 * 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.
修改指定index 下对应的value 值(注意这里 第一个参数是index,不是 key。可以配合indexOfKey(int key)先获得key所在的index)
 */
public void setValueAt(int index, E value) {
    if (mGarbage) {
        gc();
    }

    mValues[index] = value;
}

按图索骥之—>

/**
 * Gets the Object mapped from the specified key, or <code>null</code>
 * if no such mapping has been made.
通过指定的key获取对应的Object,如果没有找到对应的键值对,会默认返回null 
 */
public E get(int key) {
    return get(key, null);
}

/**
 1. Gets the Object mapped from the specified key, or the specified Object
 2. if no such mapping has been made.
 3. 通过执行的key获取对应的Object,,如果没有找到对应的键值对,会返回设置的默认值 
 */
@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];
    }
}

寻名剑(键) —>获得key

/**
获得指定index 下的key
 * */
public int keyAt(int index) {
    if (mGarbage) {
        gc();
    }
    return mKeys[index];
}

剑鞘—>获得value

/**
 * 获得指定index 对应下的value
 * */

public E valueAt(int index) {
    if (mGarbage) {
        gc();
    }

    return (E) mValues[index];
}

一个萝卜一个坑 —>*根据value 获得index*

/**
 * 根据指定的value 获得所在的index,如果没有 则返回-1
 */

public int indexOfValue(E value) {
    if (mGarbage) {
        gc();
    }

    for (int i = 0; i < mSize; i++)
        if (mValues[i] == value)
            return i;

    return -1;
}

终极必杀之受死吧妖孽,打回原形 —>clear()

/**
 * Removes all key-value mappings from this SparseArray.
 * 从SparseArray 中移除所有的key-value 键值对
 */
public void clear() {
    int n = mSize;
    Object[] values = mValues;

    for (int i = 0; i < n; i++) {
        values[i] = null;
    }

    mSize = 0;
    mGarbage = false;
}
发布了22 篇原创文章 · 获赞 44 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/JM_beizi/article/details/51148276