SparseArray结构比HashMap简单(SparseArray内部主要使用两个一维数组来保存数据,一个用来存key,一个用来存value)不须要额外的额外的数据结构(主要是针对HashMap中的HashMapEntry而言的) html
检索: android
SparseArray是使用折半查找(binarySearch)来进行检索的, 数组
当SparseArray中存在须要检索的下标时,SparseArray的性能略胜一筹(表1)。 数据结构
可是当检索的下标比较离散时,SparseArray须要使用屡次二分检索,性能显然比hash检索方式要慢一些了(表2),可是按照官方文档的说法性能差别不是很大,不超过50% 性能
因此 若是SparseArray的数据很是多, 可能就会慢一些 this
可是我的认为, 只要避免一个SparseArray全部地方都使用就能够比较检索稍慢的问题, 因此很适合使用在加强的ViewHolder中, 由于一个View中都set了一个SparseArray spa
删除
效率差很少 .net
插入: code
在正序插入数据时候,SparseArray比HashMap要快一些;HashMap无论是倒序仍是正序开销几乎是同样的;可是SparseArray的倒序插入要比正序插入要慢10倍以上,这时为何呢?咱们再看下面一段代码: orm
内存占用:
可见使用 SparseArray 的确比 HashMap 节省内存,大概节省 35%左右的内存。
Sparse arrays can be used to replace hash maps when the key is a primitive type. There are some variants for different key/value type even though not all them are publicly available.
Benefits are:
Drawbacks:
HashMap can be replaced by the followings:
SparseArray <Integer,Object> SparseBooleanArray <Integer, Boolean> SparseIntArray <Integer, Integer> SparseLongArray <Integer, Long> LongSparseArray <Long, Object> LongSparseLongArray <Long, Long> //this is not a public class //but can be copied from Android source code
In terms of memory here is an example of SparseIntArray vs HashMap for 1000 elements
SparseIntArray:
class SparseIntArray { int[] keys; int[] values; int size; }
Class = 12 + 3 * 4 = 24 bytes
Array = 20 + 1000 * 4 = 4024 bytes
Total = 8,072 bytes
HashMap:
class HashMap<K, V> { Entry<K, V>[] table; Entry<K, V> forNull; int size; int modCount; int threshold; Set<K> keys Set<Entry<K, V>> entries; Collection<V> values; }
Class = 12 + 8 * 4 = 48 bytes
Entry = 32 + 16 + 16 = 64 bytes
Array = 20 + 1000 * 64 = 64024 bytes
Total = 64,136 bytes]
参考:
http://android-performance.com/android/2014/02/10/android-sparsearray-vs-hashmap.html
http://blog.csdn.net/zimo2013/article/details/39692245
http://stackoverflow.com/questions/25560629/sparsearray-vs-hashmap