1.SpareArray和普通的HanshMap有什么区别?
SpareArray是整数和对象的映射表,在整数和对象之间的映射的时候,比HashMap更加高效。使用整数键省略了自动装箱过程,每一个键和值之间的关系也不会使用到额外的entity对象,spareArry是用两个数组来实现的映射关系。
private int[] mKeys;
private Object[] mValues;
数据结构使用数组来建立映射关系。它使用二分查找来找每一个value,它不适合存储大量的数据结构。它比传统的hashMap慢,它是增加和删除数据都需要使用二分查找数据。对于小规模数据性能较好。
342 private static int binarySearch(int[] a, int start, int len, int key) {
343 int high = start + len, low = start - 1, guess;
344
345 while (high - low > 1) {
346 guess = (high + low) / 2;
347
348 if (a[guess] < key)
349 low = guess;
350 else
351 high = guess;
352 }
353
354 if (high == start + len)
355 return ~(start + len);
356 else if (a[high] == key)
357 return high;
358 else
359 return ~high;
360 }
为了提高性能,它在删除数据时,不会立即删除数据,而是将数据标记为删除状态,方便后面重用,在垃圾回收的时候会压缩这个删除的条目。垃圾回收会在扩容数据和获取spareArray大小时得到执行。
90 public void delete(int key) {
91 int i = binarySearch(mKeys, 0, mSize, key);
92
93 if (i >= 0) {
94 if (mValues[i] != DELETED) {
95 mValues[i] = DELETED;
96 mGarbage = true;
97 }
98 }
99 }
108 private void gc() {
109 // Log.e("SparseArray", "gc start with " + mSize);
110
111 int n = mSize;
112 int o = 0;
113 int[] keys = mKeys;
114 Object[] values = mValues;
115
116 for (int i = 0; i < n; i++) {
117 Object val = values[i];
118
119 if (val != DELETED) {
120 if (i != o) {
121 keys[o] = keys[i];
122 values[o] = val;
123 }
124
125 o++;
126 }
127 }
128
129 mGarbage = false;
130 mSize = o;
131
132 // Log.e("SparseArray", "gc end with " + mSize);
133 }
191 public int size() {
192 if (mGarbage) {
193 gc();
194 }
195
196 return mSize;
197 }
SpareArray的轻量级高效的数据数据结构,他主要是用来保存以int类型为键的键值对。在数据量不大的情况下比比较高效。相比HashMap有一些不同点
- SpareArray内部使用数组来保存键值对,并且键必须为整数,HashMap是使用entity来保存键值对,并且采用了数组加上链表的(红黑树)方式保存entity,对键和值的类型没有要求。
- SpareArray插入和删除数据的时候都是采用二分查找的方式来查找数据,时间复杂读为O(logn),hashMap的查找时间复杂度在理想情况下是O(1),
- SpareArray优化了删除操作,删除据时,会把数据标记为删除状态,不回收内存,只有在扩容或者新增数据的时候才会回收内存。