詳解Android的內(nèi)存優(yōu)化--LruCache
概念:
LruCache
什么是LruCache?
LruCache實(shí)現(xiàn)原理是什么?
這兩個(gè)問(wèn)題其實(shí)可以作為一個(gè)問(wèn)題來(lái)回答,知道了什么是 LruCache,就只然而然的知道 LruCache 的實(shí)現(xiàn)原理;Lru的全稱(chēng)是Least Recently Used ,近期最少使用的!所以我們可以推斷出 LruCache 的實(shí)現(xiàn)原理:把近期最少使用的數(shù)據(jù)從緩存中移除,保留使用最頻繁的數(shù)據(jù),那具體代碼要怎么實(shí)現(xiàn)呢,我們進(jìn)入到源碼中看看。
LruCache源碼分析
public class LruCache<K, V> {
//緩存 map 集合,為什么要用LinkedHashMap
//因?yàn)闆](méi)錯(cuò)取了緩存值之后,都要進(jìn)行排序,以確保
//下次移除的是最少使用的值
private final LinkedHashMap<K, V> map;
//當(dāng)前緩存的值
private int size;
//最大值
private int maxSize;
//添加到緩存中的個(gè)數(shù)
private int putCount;
//創(chuàng)建的個(gè)數(shù)
private int createCount;
//被移除的個(gè)數(shù)
private int evictionCount;
//命中個(gè)數(shù)
private int hitCount;
//丟失個(gè)數(shù)
private int missCount;
//實(shí)例化 Lru,需要傳入緩存的最大值
//這個(gè)最大值可以是個(gè)數(shù),比如對(duì)象的個(gè)數(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);
}
//通過(guò) 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++;
}
//如果沒(méi)有,用戶(hù)可以去創(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);
}
}
//這里沒(méi)有移除,只是改變了位置
if (mapValue != null) {
entryRemoved(false, key, createdValue, mapValue);
return mapValue;
} else {
//判斷緩存是否越界
trimToSize(maxSize);
return createdValue;
}
}
//添加緩存,跟上面這個(gè)方法的 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;
}
//檢測(cè)緩存是否越界
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!");
}
//如果沒(méi)有,則返回
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;
}
//移除最后一個(gè),也就是最少使用的緩存
key = toEvict.getKey();
value = toEvict.getValue();
map.remove(key);
size -= safeSizeOf(key, value);
evictionCount++;
}
entryRemoved(true, key, value, null);
}
}
//手動(dòng)移除,用戶(hù)調(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;
}
//這里用戶(hù)可以重寫(xiě)它,實(shí)現(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;
}
//這個(gè)方法要特別注意,跟我們實(shí)例化 LruCache 的 maxSize 要呼應(yīng),怎么做到呼應(yīng)呢,比如 maxSize 的大小為緩存的個(gè)數(shù),這里就是 return 1就 ok,如果是內(nèi)存的大小,如果5M,這個(gè)就不能是個(gè)數(shù) 了,這是應(yīng)該是每個(gè)緩存 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 使用
先來(lái)看兩張內(nèi)存使用的圖

圖-1

圖-2
以上內(nèi)存分析圖所分析的是同一個(gè)應(yīng)用的數(shù)據(jù),唯一不同的是圖-1沒(méi)有使用 LruCache,而圖-2使用了 LruCache;可以非常明顯的看到,圖-1的內(nèi)存使用明顯偏大,基本上都是在30M左右,而圖-2的內(nèi)存使用情況基本上在20M左右。這就足足省了將近10M的內(nèi)存!
ok,下面把實(shí)現(xiàn)代碼貼出來(lái)
/**
* 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 ;
/*實(shí)例化LruCache*/
mLruCache = new LruCache<String,Bitmap>(mTotalSize/5){
/*當(dāng)緩存大于我們?cè)O(shè)定的最大值時(shí),會(huì)調(diào)用這個(gè)方法,我們可以用來(lái)做內(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) ;
}
/*獲取每個(gè) 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算法實(shí)現(xiàn)的一種緩存機(jī)制;
- Lru算法的原理是把近期最少使用的數(shù)據(jù)給移除掉,當(dāng)然前提是當(dāng)前數(shù)據(jù)的量大于設(shè)定的最大值。
- LruCache 沒(méi)有真正的釋放內(nèi)存,只是從 Map中移除掉數(shù)據(jù),真正釋放內(nèi)存還是要用戶(hù)手動(dòng)釋放。
以上就是本文的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,同時(shí)也希望多多支持腳本之家!
相關(guān)文章
Android開(kāi)發(fā)之APP安裝后在桌面上不顯示應(yīng)用圖標(biāo)的解決方法
這篇文章主要介紹了Android開(kāi)發(fā)之APP安裝后在桌面上不顯示應(yīng)用圖標(biāo)的解決方法,涉及Android activity相關(guān)屬性設(shè)置技巧,需要的朋友可以參考下2017-07-07
Android中使用Intent在Activity之間傳遞對(duì)象(使用Serializable或者Parcelable)的
這篇文章主要介紹了 Android中使用Intent在Activity之間傳遞對(duì)象(使用Serializable或者Parcelable)的方法的相關(guān)資料,需要的朋友可以參考下2016-01-01
Android 中ViewPager中使用WebView的注意事項(xiàng)
這篇文章主要介紹了Android 中ViewPager中使用WebView的注意事項(xiàng)的相關(guān)資料,希望通過(guò)本文大家在使用過(guò)程中遇到這樣的問(wèn)題解決,需要的朋友可以參考下2017-09-09
Android編程實(shí)現(xiàn)簡(jiǎn)單文件瀏覽器功能
這篇文章主要介紹了Android編程實(shí)現(xiàn)簡(jiǎn)單文件瀏覽器功能,結(jié)合實(shí)例形式分析了Android文件管理器的布局、文件與目錄的遍歷、權(quán)限控制等相關(guān)操作技巧,需要的朋友可以參考下2018-01-01
Android中系統(tǒng)自帶鎖WalkLock與KeyguardLock用法實(shí)例詳解
這篇文章主要介紹了Android中系統(tǒng)自帶鎖WalkLock與KeyguardLock用法,結(jié)合實(shí)例形式較為詳細(xì)的分析了WalkLock與KeyguardLock的功能、作用、使用方法與相關(guān)注意事項(xiàng),需要的朋友可以參考下2016-01-01
Android基于ViewDragHelper仿QQ5.0側(cè)滑界面效果
這篇文章主要介紹了Android基于ViewDragHelper仿QQ5.0側(cè)滑界面效果,具有一定的,感興趣的小伙伴們可以參考一下2016-07-07
Android fragment 轉(zhuǎn)場(chǎng)動(dòng)畫(huà)創(chuàng)建步驟
在 Android 中,可以使用 setCustomAnimations() 方法來(lái)繪制自定義的 Fragment 轉(zhuǎn)場(chǎng)動(dòng)畫(huà),本文分步驟給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-03-03
ScrollView嵌套ListView滑動(dòng)沖突的解決方法
這篇文章主要介紹了ScrollView嵌套ListView滑動(dòng)沖突的解決方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-11-11
Flutter質(zhì)感設(shè)計(jì)之進(jìn)度條
這篇文章主要為大家詳細(xì)介紹了Flutter質(zhì)感設(shè)計(jì)之進(jìn)度條,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-08-08

