memoized 1.4.2
memoized: ^1.4.2 copied to clipboard
Decorators to cache returned values, it helps in reducing the execution time of the function by using LRU Caching.
example/memoized_example.dart
import 'package:memoized/memoized.dart';
extension RangeGenExt on int {
Iterable<int> to(int target) sync* {
int start = this;
while (start <= target) {
yield start;
start++;
}
}
}
extension IterableNumberExt on Iterable<int> {
int sum() => reduce((value, element) => value + element);
}
void time<V>(V Function() fn) {
final watch = Stopwatch()..start();
watch.start();
final result = fn();
watch.stop();
final elapsed = '${watch.elapsedMilliseconds} ms';
print('[${elapsed.padLeft(7)}] $result returned.');
}
Future<void> timeAsync<V>(Future<V> future) async {
final watch = Stopwatch()..start();
watch.start();
final result = await future;
watch.stop();
final elapsed = '${watch.elapsedMilliseconds} ms';
print('[${elapsed.padLeft(7)}] $result returned.');
}
void main() async {
Iterable<int> numbers = 1.to(30000000);
final calculateSum = (() => numbers.sum()).memo;
print('===== Memoized =====');
time(calculateSum);
time(calculateSum); // It returns the memoized value.
late final Memoized1<int, int> fib;
fib = Memoized1((int n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
});
print('\n===== Memoized1 =====');
time(() => fib(60));
}