詳解Android的內(nèi)存優(yōu)化--LruCache
概念:
LruCache
什么是LruCache?
LruCache實現(xiàn)原理是什么?
這兩個問題其實可以作為一個問題來回答,知道了什么是 LruCache,就只然而然的知道 LruCache 的實現(xiàn)原理;Lru的全稱是Least Recently Used ,近期最少使用的!所以我們可以推斷出 LruCache 的實現(xiàn)原理:把近期最少使用的數(shù)據(jù)從緩存中移除,保留使用最頻繁的數(shù)據(jù),那具體代碼要怎么實現(xiàn)呢,我們進(jìn)入到源碼中看看。
LruCache源碼分析
public class LruCache<K, V> {
//緩存 map 集合,為什么要用LinkedHashMap
//因為沒錯取了緩存值之后,都要進(jìn)行排序,以確保
//下次移除的是最少使用的值
private final LinkedHashMap<K, V> map;
//當(dāng)前緩存的值
private int size;
//最大值
private int maxSize;
//添加到緩存中的個數(shù)
private int putCount;
//創(chuàng)建的個數(shù)
private int createCount;
//被移除的個數(shù)
private int evictionCount;
//命中個數(shù)
private int hitCount;
//丟失個數(shù)
private int missCount;
//實例化 Lru,需要傳入緩存的最大值
//這個最大值可以是個數(shù),比如對象的個數(shù),也可以是內(nèi)存的大小
//比如,最大內(nèi)存只能緩存5兆
public LruCache(int maxSize) {
if (maxSize <= 0) {
throw new IllegalArgumentException("maxSize <= 0");
}
this.maxSize = maxSize;
this.map = new LinkedHashMap<K, V>(0, 0.75f, true);
}
//重置最大緩存的值
public void resize(int maxSize) {
if (maxSize <= 0) {
throw new IllegalArgumentException("maxSize <= 0");
}
synchronized (this) {
this.maxSize = maxSize;
}
trimToSize(maxSize);
}
//通過 key 獲取緩存值
public final V get(K key) {
if (key == null) {
throw new NullPointerException("key == null");
}
V mapValue;
synchronized (this) {
mapValue = map.get(key);
if (mapValue != null) {
hitCount++;
return mapValue;
}
missCount++;
}
//如果沒有,用戶可以去創(chuàng)建
V createdValue = create(key);
if (createdValue == null) {
return null;
}
synchronized (this) {
createCount++;
mapValue = map.put(key, createdValue);
if (mapValue != null) {
// There was a conflict so undo that last put
map.put(key, mapValue);
} else {
//緩存的大小改變
size += safeSizeOf(key, createdValue);
}
}
//這里沒有移除,只是改變了位置
if (mapValue != null) {
entryRemoved(false, key, createdValue, mapValue);
return mapValue;
} else {
//判斷緩存是否越界
trimToSize(maxSize);
return createdValue;
}
}
//添加緩存,跟上面這個方法的 create 之后的代碼一樣的
public final V put(K key, V value) {
if (key == null || value == null) {
throw new NullPointerException("key == null || value == null");
}
V previous;
synchronized (this) {
putCount++;
size += safeSizeOf(key, value);
previous = map.put(key, value);
if (previous != null) {
size -= safeSizeOf(key, previous);
}
}
if (previous != null) {
entryRemoved(false, key, previous, value);
}
trimToSize(maxSize);
return previous;
}
//檢測緩存是否越界
private void trimToSize(int maxSize) {
while (true) {
K key;
V value;
synchronized (this) {
if (size < 0 || (map.isEmpty() && size != 0)) {
throw new IllegalStateException(getClass().getName()
+ ".sizeOf() is reporting inconsistent results!");
}
//如果沒有,則返回
if (size <= maxSize) {
break;
}
//以下代碼表示已經(jīng)超出了最大范圍
Map.Entry<K, V> toEvict = null;
for (Map.Entry<K, V> entry : map.entrySet()) {
toEvict = entry;
}
if (toEvict == null) {
break;
}
//移除最后一個,也就是最少使用的緩存
key = toEvict.getKey();
value = toEvict.getValue();
map.remove(key);
size -= safeSizeOf(key, value);
evictionCount++;
}
entryRemoved(true, key, value, null);
}
}
//手動移除,用戶調(diào)用
public final V remove(K key) {
if (key == null) {
throw new NullPointerException("key == null");
}
V previous;
synchronized (this) {
previous = map.remove(key);
if (previous != null) {
size -= safeSizeOf(key, previous);
}
}
if (previous != null) {
entryRemoved(false, key, previous, null);
}
return previous;
}
//這里用戶可以重寫它,實現(xiàn)數(shù)據(jù)和內(nèi)存回收操作
protected void entryRemoved(boolean evicted, K key, V oldValue, V newValue) {}
protected V create(K key) {
return null;
}
private int safeSizeOf(K key, V value) {
int result = sizeOf(key, value);
if (result < 0) {
throw new IllegalStateException("Negative size: " + key + "=" + value);
}
return result;
}
//這個方法要特別注意,跟我們實例化 LruCache 的 maxSize 要呼應(yīng),怎么做到呼應(yīng)呢,比如 maxSize 的大小為緩存的個數(shù),這里就是 return 1就 ok,如果是內(nèi)存的大小,如果5M,這個就不能是個數(shù) 了,這是應(yīng)該是每個緩存 value 的 size 大小,如果是 Bitmap,這應(yīng)該是 bitmap.getByteCount();
protected int sizeOf(K key, V value) {
return 1;
}
//清空緩存
public final void evictAll() {
trimToSize(-1); // -1 will evict 0-sized elements
}
public synchronized final int size() {
return size;
}
public synchronized final int maxSize() {
return maxSize;
}
public synchronized final int hitCount() {
return hitCount;
}
public synchronized final int missCount() {
return missCount;
}
public synchronized final int createCount() {
return createCount;
}
public synchronized final int putCount() {
return putCount;
}
public synchronized final int evictionCount() {
return evictionCount;
}
public synchronized final Map<K, V> snapshot() {
return new LinkedHashMap<K, V>(map);
}
}
LruCache 使用
先來看兩張內(nèi)存使用的圖

圖-1

圖-2
以上內(nèi)存分析圖所分析的是同一個應(yīng)用的數(shù)據(jù),唯一不同的是圖-1沒有使用 LruCache,而圖-2使用了 LruCache;可以非常明顯的看到,圖-1的內(nèi)存使用明顯偏大,基本上都是在30M左右,而圖-2的內(nèi)存使用情況基本上在20M左右。這就足足省了將近10M的內(nèi)存!
ok,下面把實現(xiàn)代碼貼出來
/**
* Created by gyzhong on 15/4/5.
*/
public class LruPageAdapter extends PagerAdapter {
private List<String> mData ;
private LruCache<String,Bitmap> mLruCache ;
private int mTotalSize = (int) Runtime.getRuntime().totalMemory();
private ViewPager mViewPager ;
public LruPageAdapter(ViewPager viewPager ,List<String> data){
mData = data ;
mViewPager = viewPager ;
/*實例化LruCache*/
mLruCache = new LruCache<String,Bitmap>(mTotalSize/5){
/*當(dāng)緩存大于我們設(shè)定的最大值時,會調(diào)用這個方法,我們可以用來做內(nèi)存釋放操作*/
@Override
protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) {
super.entryRemoved(evicted, key, oldValue, newValue);
if (evicted && oldValue != null){
oldValue.recycle();
}
}
/*創(chuàng)建 bitmap*/
@Override
protected Bitmap create(String key) {
final int resId = mViewPager.getResources().getIdentifier(key,"drawable",
mViewPager.getContext().getPackageName()) ;
return BitmapFactory.decodeResource(mViewPager.getResources(),resId) ;
}
/*獲取每個 value 的大小*/
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getByteCount();
}
} ;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View view = LayoutInflater.from(container.getContext()).inflate(R.layout.view_pager_item, null) ;
ImageView imageView = (ImageView) view.findViewById(R.id.id_view_pager_item);
Bitmap bitmap = mLruCache.get(mData.get(position));
imageView.setImageBitmap(bitmap);
container.addView(view);
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public int getCount() {
return mData.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
總結(jié)
- LruCache 是基于 Lru算法實現(xiàn)的一種緩存機(jī)制;
- Lru算法的原理是把近期最少使用的數(shù)據(jù)給移除掉,當(dāng)然前提是當(dāng)前數(shù)據(jù)的量大于設(shè)定的最大值。
- LruCache 沒有真正的釋放內(nèi)存,只是從 Map中移除掉數(shù)據(jù),真正釋放內(nèi)存還是要用戶手動釋放。
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關(guān)文章
Android開發(fā)之APP安裝后在桌面上不顯示應(yīng)用圖標(biāo)的解決方法
這篇文章主要介紹了Android開發(fā)之APP安裝后在桌面上不顯示應(yīng)用圖標(biāo)的解決方法,涉及Android activity相關(guān)屬性設(shè)置技巧,需要的朋友可以參考下2017-07-07
Android中使用Intent在Activity之間傳遞對象(使用Serializable或者Parcelable)的
這篇文章主要介紹了 Android中使用Intent在Activity之間傳遞對象(使用Serializable或者Parcelable)的方法的相關(guān)資料,需要的朋友可以參考下2016-01-01
Android 中ViewPager中使用WebView的注意事項
這篇文章主要介紹了Android 中ViewPager中使用WebView的注意事項的相關(guān)資料,希望通過本文大家在使用過程中遇到這樣的問題解決,需要的朋友可以參考下2017-09-09
Android中系統(tǒng)自帶鎖WalkLock與KeyguardLock用法實例詳解
這篇文章主要介紹了Android中系統(tǒng)自帶鎖WalkLock與KeyguardLock用法,結(jié)合實例形式較為詳細(xì)的分析了WalkLock與KeyguardLock的功能、作用、使用方法與相關(guān)注意事項,需要的朋友可以參考下2016-01-01
Android基于ViewDragHelper仿QQ5.0側(cè)滑界面效果
這篇文章主要介紹了Android基于ViewDragHelper仿QQ5.0側(cè)滑界面效果,具有一定的,感興趣的小伙伴們可以參考一下2016-07-07
Android fragment 轉(zhuǎn)場動畫創(chuàng)建步驟
在 Android 中,可以使用 setCustomAnimations() 方法來繪制自定義的 Fragment 轉(zhuǎn)場動畫,本文分步驟給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-03-03
Flutter質(zhì)感設(shè)計之進(jìn)度條
這篇文章主要為大家詳細(xì)介紹了Flutter質(zhì)感設(shè)計之進(jìn)度條,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-08-08

