Do I need to cache Dart property result in release flutter VM for the best of the best performance?
It dartpad, cache will improve performance.
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}');
}
Result
counting...
counting...
Me? rich
counting...
Me cool? rich
Property method are side effect free.
That entirely depends on how expensive the calculation is and how often the result is requested from the property.
Dart has nice syntax for caching if you actually do want to cache
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';
To reset the cache because some value the result depends on has changed, just set it to null
save(num amt) {
moneys.add(amt);
_total = null;
_whoAmI = null;
_uberWhoAmI = null;
}
and the next time a property is accessed the values will be recalculated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With