Kya*_*Tun 1 micro-optimization dart flutter
我是否需要将Dart属性缓存到发布抖动的VM中以获得最佳的最佳性能?
如果使用dartpad,缓存会提高性能。
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}');
}
Run Code Online (Sandbox Code Playgroud)
结果
counting...
counting...
Me? rich
counting...
Me cool? rich
Run Code Online (Sandbox Code Playgroud)
属性方法无副作用。
这完全取决于计算的成本以及从属性请求结果的频率。
如果您确实想缓存,Dart具有很好的缓存语法
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';
Run Code Online (Sandbox Code Playgroud)
要重置缓存,因为结果所依赖的某些值已更改,只需将其设置为 null
save(num amt) {
moneys.add(amt);
_total = null;
_whoAmI = null;
_uberWhoAmI = null;
}
Run Code Online (Sandbox Code Playgroud)
下次访问属性时,将重新计算值。
| 归档时间: |
|
| 查看次数: |
274 次 |
| 最近记录: |