2017-08-31 100 views
0

我是否需要將Dart屬性結果緩存在發佈抖動VM中以獲得最佳性能?Dart屬性結果是否需要緩存?

它的飛鏢緩存將提高性能。

class Piggybank { 
    List<num> moneys = []; 
    Piggybank(); 

    save(num amt) { 
    moneys.add(amt); 
    } 

    num get total { 
    print('counting...'); 
    return moneys.reduce((x, y) => x + y); 
    } 

    String get whoAmI { 
    return total < 10 ? 'poor' : total < 10000 ? 'ok' : 'rich'; 
    } 

    String get uberWhoAmI { 
    num _total = total; 
    return _total < 10 ? 'poor' : _total < 10000 ? 'ok' : 'rich'; 
    } 
} 

void main() { 
    var bank = new Piggybank(); 
    new List<num>.generate(10000, (i) => i + 1.0)..forEach((x) => bank.save(x)); 
    print('Me? ${bank.whoAmI}'); 
    print('Me cool? ${bank.uberWhoAmI}'); 
} 

結果

counting... 
counting... 
Me? rich 
counting... 
Me cool? rich 

屬性方法是自由的副作用。

回答

3

這完全取決於計算的成本是多少,以及從屬性請求結果的頻率。

飛鏢有緩存很好的語法,如果你真的不想要緩存

num _total; 
    num get total { 
    print('counting...'); 
    return _total ??= moneys.reduce((x, y) => x + y); 
    } 

    String _whoAmI; 
    String get whoAmI => 
    _whoAmI ??= total < 10 ? 'poor' : total < 10000 ? 'ok' : 'rich'; 


    String _uberWhoAmI; 
    String get uberWhoAmI => 
    _uberWhoAmI ??= total < 10 ? 'poor' : _total < 10000 ? 'ok' : 'rich'; 

要因爲一些值結果取決於改變重置緩存,只需將其設置爲null

save(num amt) { 
    moneys.add(amt); 
    _total = null; 
    _whoAmI = null; 
    _uberWhoAmI = null; 
    } 

並且下次訪問屬性時,這些值將被重新計算。

+0

所以答案是否定的? Dart有很好的任務,但仍然需要使緩存失效對性能改進來說太麻煩了。 –

+0

不,沒有「需要」。這取決於你的具體使用情況。請求結果的頻率如何,計算成本有多高,緩存消耗多少內存,多麼複雜的是失效,...... 如果編譯器或CPU自己優化它,它也取決於局部性具體的用例。如果您從事性能,內存消耗......關鍵代碼,您需要進行基準測試,以確定在具體情況下哪種方法最好。 –

+0

'whoAmI'方法訪問'total' _variable_兩次,這樣做兩次調用getter方法。一般假設是它會調用一次。爲什麼Dart不會自動緩存結果,_assuming_ getter方法不能更改對象狀態? –