Android SparseArray浅析

来源:互联网 发布:php tp框架 c函数 编辑:程序博客网 时间:2024/06/06 01:19

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.

SparseArray使用整数映射对象。和其他的对象数组有很大的差别。因为其避免了自动装箱并且不依赖于外部对象映射,所以比HashMap更节省内存。

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%.

请注意SparseArray容器将它的映射保存到数组结构中,使用折半查找查找键值,一般不适用于大量数据。他比HashMap的效率要低,因为需要使用二分查找法搜索和插入、删除数据,如果容器中有百条数据,两者的性能差异并不明显,相差不到50%。

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.

为了改善性能,SparseArray在删除键值是做了优化:并不是直接压缩数组,而是将删除的内容标记为已删除。数据可以重复使用相同的键值,或在后边的步骤中将已删除的条目压缩数组。垃圾回收容器需要一直查询键值时候是可恢复的。


所谓稀疏数组就是数组中大部分的内容值都未被使用(或都为零),在数组中仅有少部分的空间使用。因此造成内存空间的浪费,为了节省内存空间,并且不影响数组中原有的内容值,我们可以采用一种压缩的方式来表示稀疏数组的内容。

假设有一个9*7的数组,其内容如下:

这里写图片描述

在此数组中,共有63个空间,但却只使用了5个元素,造成58个元素空间的浪费。以下我们就使用稀疏数组重新来定义这个数组:

这里写图片描述

其中在稀疏数组中第一部分所记录的是原数组的列数和行数以及元素使用的个数、第二部分所记录的是原数组中元素的位置和内容。经过压缩之后,原来需要声明大小为63的数组,而使用压缩后,只需要声明大小为6*3的数组,仅需18个存储空间。

我们再来看看源码中SparseArray到底做了哪些事情:

这里写图片描述

在源码中可以看到:SparseArray有增删改查、大小方法。

由于是采用二分法查找键的位置,所以找不到时返回小于0的数值,而不是返回-1。返回的负值是表示它在找不到时所在的位置。

SparseArray是android里为<Interger,Object>这样的Hashmap而专门写的类,SparseArray不需要开辟内存空间来额外存储外部映射,从而节省内存。目的是提高内存效率,其核心是折半查找函数(binarySearch)。注意内存二字很重要,因为它仅仅提高内存效率,而不是提高执行效率,所以也决定它只适用于android系统。

参考:http://blog.csdn.net/u013493809/article/details/21699121

0 0