java层优化:
采用android特有的数据结构:
用
android.util.SparseArray
android.util.SparseBooleanArray
android.util.SparseIntArray
替代
java.util.ArrayList
下面就介绍下android.util.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.
* /
上面是官网上的说明,大概的意思是,它可以看做是一种Integer对Object的map集合,它不像普通的ArrayList集合,它具有下标索引,相比于HashMap,它具有更高效的内存使用。底层结合二分查找算法,效果比普通的要高效很多。
使用如下:
SparseArray<String> stringSparseArray = new SparseArray<>();
for (int i = 0; i < 10; i++) {
stringSparseArray.put(i,"item " + i);
}
stringSparseArray.get( key );
底层二分查找算法如下:
static int binarySearch(long[] array, int size, long value) {
int lo = 0;
int hi = size - 1;
while (lo <= hi) {
final int mid = (lo + hi) >>> 1;//中间索引
final long midVal = array[mid];
if (midVal < value) {//如果值比中间值大,则往大的一边继续二分查找
lo = mid + 1;
} else if (midVal > value) {//如果值比中间值小,则往小的一边继续二分查找
hi = mid - 1;
} else {
return mid; // value found
}
}
return ~lo; // value not present
}
感兴趣的话,可以看看底层实现的代码。
好了,今天的优化就到这了。好困啊。。。。