memoized 1.4.7
memoized: ^1.4.7 copied to clipboard
Decorators to cache returned values, it helps in reducing the execution time of the function by using LRU Caching.
Overview #
-
saves the previously computed value
final sum = Memoized(() => 1.to(999999999).sum()); print(sum()); print(sum()); // returned immediately
-
with LRU Cache (Fibonacci series)
// Memoized1<ReturnType, ArgumentType> late final Memoized1<int, int> fib; fib = Memoized1((int n) { if (n <= 1) return n; return fib(n-1) + fib(n-2); }); print(fib(80));
Memoized1~5 maintains an LRU cache that uses a function argument as key and the result value according to the function arguments as value, as follows.
LruMap<ArgumentType, ReturnType>
Installing #
dependencies:
memoized:
import 'package:memoized/memoized.dart';
Memoized #
Wrap a function to store the previously computed value and return this value on the next call.
-
Basic
Iterable<int> numbers = 1.to(30000000); final calculateSum = (() => numbers.sum()).memo; print(time(calculateSum)); print(time(calculateSum)); // It returns the memoized value.
-
expire
Iterable<int> numbers = 1.to(30000000); final calculateSum = (() => numbers.sum()).memo; print(calculateSum()); numbers = 1.to(9043483); calculateSum.expire() // not computed numbers = 1.to(45000000); calculateSum.expire() // not computed final value = calculateSum() // recomputed at this point.
-
in Class #
class IntervalTimer { final List<Duration> timers = [/* durations */]; late final totalDuration = _totalDurationImpl.memo; Duration _totalDurationImpl() => timers.fold<Duration>( Duration.zero, (p, v) => p + v ); }
Memoized1 ~ 5 #
Decorator to wrap a function with a memoizing callable that saves up to the capacity most recent calls.
-
fibonacci
// Memoized1<ReturnType, ArgumentType> late final Memoized1<int, int> fib; fib = Memoized1((int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); }); print(fib(90));
-
expire
print(await fetchDoument('hello')); // returned after 2 seconds. fetchDocument.expire('hello'); print(await fetchDoument('hello')); // also returned after 2 seconds.
-
in Class
class Test { late final Memoized1<int, int> fib = Memoized1( (n) => n <= 1 ? n : fib(n - 1) + fib(n - 2), ); }
-
capacity
class Test { late final Memoized1<int, int> fib = Memoized1( (n) => n <= 1 ? n : fib(n - 1) + fib(n - 2), capacity: 10, // default == 128 ); }