标签:sparcearray 性能优化 二分查找 performance
int MAX = 100000; long start = System.currentTimeMillis(); HashMap<Integer, String> hash = new HashMap<Integer, String>(); for (int i = 0; i < MAX; i++) { hash.put(i, String.valueOf(i)); } long ts = System.currentTimeMillis() - start;代码2:
int MAX = 100000; long start = System.currentTimeMillis(); SparseArray<String> sparse = new SparseArray<String>(); for (int i = 0; i < MAX; i++) { sparse.put(i, String.valueOf(i)); } long ts = System.currentTimeMillis() - start;上面两段代码中,我们分别用HashMap和SpaseArray正序插入100000条数据,数据如下:
# | 代码1 | 代码2 | ||
---|---|---|---|---|
时间 | 10750ms | 7429ms | ||
空间 | 13.2M | 8.26M |
int MAX = 100000; long start = System.currentTimeMillis(); HashMap<Integer, String> hash = new HashMap<Integer, String>(); for (int i = 0; i < MAX; i++) { hash.put(MAX - i -1, String.valueOf(i)); } long ts = System.currentTimeMillis() - start;代码4:
int MAX = 100000; long start = System.currentTimeMillis(); SparseArray<String> sparse = new SparseArray<String>(); for (int i = 0; i < MAX; i++) { sparse.put(MAX - i -1, String.valueOf(i)); } long ts = System.currentTimeMillis() - start;
# | 代码1 | 代码2 | 代码3 | 代码4 |
---|---|---|---|---|
1 | 10750ms | 7429ms | 10862ms | 90527ms |
2 | 10718ms | 7386ms | 10711ms | 87990ms |
3 | 10816ms | 7462ms | 11033ms | 88259ms |
4 | 10943ms | 7386ms | 10854ms | 88474ms |
public void put(int key, E value) { int i = binarySearch(mKeys, 0, 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 = ~binarySearch(mKeys, 0, mSize, key); } …………
private static int binarySearch(int[] a, int start, int len, int key) { int high = start + len, low = start - 1, guess; while (high - low > 1) { guess = (high + low) / 2; if (a[guess] < key) low = guess; else high = guess; } if (high == start + len) return ~(start + len); else if (a[high] == key) return high; else return ~high; }
HashMap<Integer, E> hashMap = new HashMap<Integer, E>();时,我们可以使用如下的方式来取得更好的性能.
Android应用性能优化之使用SparseArray替代HashMap
标签:sparcearray 性能优化 二分查找 performance
原文地址:http://blog.csdn.net/hlglinglong/article/details/45462773