memoized 1.4.0
memoized: ^1.4.0 copied to clipboard
Decorators to cache returned values which helps in reducing the execution time of the function by using LRU Caching.
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 #
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));
-
async
late final Memoized1Async<String, String> fetchDocument; fetchDocument = Memoized1Async((url) async { await Future.delayed(const Duration(seconds: 2)); if (url == 'hello') return 'hello, memoized'; return 'welcome'; }); print(await fetchDocument('hello')); print(await fetchDocument('hello')); // returned immediately print(await fetchDocument('test')); print(await fetchDocument('test')); // returned immediately
-
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
late final Memoized1Async<String, String> fetchDocument; fetchDocument = Memoized1Async( (url) async { await Future.delayed(const Duration(seconds: 2)); if (url == 'hello') return 'hello, memoized'; return 'welcome'; }, capacity: 10, // modified, default == 128 );