在程式設計中我們經常會進行一些全局緩存設計,諸如使用靜态或者全局根字段來引用某個對象,以便一次建立多次使用。
如:
class bigdata
{
}
class program
static bigdata cache;
public static bigdata datacache
{
get
{
if (cache== null) cache= new bigdata();
return cache;
}
}
但是這樣做在某些時候會存在一些弊端,如:
1. 當datacache并沒有被頻繁使用,甚至因為某些原因僅僅被使用了一次時會造成記憶體資源的浪費。
2. 由于gc隻能回收不可達對象,是以即便記憶體不足,gc也無法回收這些閑置資源。
這時建議你使用 weakreference 來重構你的程式,以便獲得更好的系統性能。
weakreference :“弱引用”,即在引用對象的同時仍然允許對該對象進行垃圾回收。
使用弱引用後,不應該再使用強引用,有關細節可以參考sdk幫助文檔。
~bigdata()
console.writeline("destory...");
public void test()
console.writeline("test");
static weakreference cache = new weakreference(null);
bigdata data = cache.target as bigdata;
if (data == null)
{
data = new bigdata();
cache.target = data;
}
return data;
static void main(string[] args)
datacache.test();
gc.collect();
改進後的程式,我們依舊可以實作我們緩存的目的,而gc也可以在合時的時候釋放cache占用的記憶體。
.net中的緩存功能多采用了類似的設計。
當然并非要求所有的場合都适合使用弱引用。
補充:
弱引用分為"短弱引用(short week reference)"和"長弱引用(long week reference)",其差別是長弱引用在對象的finalize方法被gc調用後依然追蹤對象。基于安全考慮,不推薦使用長弱引用。
是以建議使用
weakreference wr = new weakreference(object);
或
weakreference wr = new weakreference(object, false);