Skip to content

Memo

Memo is a class callable with memoization logic which it stores computation results in cache, and retrieve that same information from the cache the next time it’s needed instead of computing it again.

Memoization is a powerful trick that can help speed up our code, especially when dealing with repetitive and heavy computing functions.

Syntax

Memo<T, A>(
T computeValue(A arg), [
MemoInterceptor<T, A>? interceptor,
]);

Memo accepts these properties:

  • computeValue : A method that takes an argument of type A and returns a value of T type. This is the core function that will be memoized.
  • interceptor: A MemoInterceptor that allows you to intercept the memoization function calls and modify the memoization process. Reactter providers some interceptors:

Methods

Memo provides the following methods that will help you manipulate the cache as you wish:

  • get : Returns the cached value by argument passed.
    • Syntax:
      T? get(A arg);
  • remove : Removes the cached value by argument passed.
    • Syntax:
      T? remove(A arg);
  • clear : Removes all cached data.
    • Syntax:
      void clear();

Example

Here’s an example of factorial using Memo :

1
late final factorialMemo = Memo(calculateFactorial);
2
3
/// A factorial(n!) represents the multiplication of all numbers between 1 and n.
4
/// For example, factorial(3) equals 3 x 2 x 1, which is 6.
5
BigInt calculateFactorial(int number) {
6
if (number == 0) return BigInt.one;
7
return BigInt.from(number) * factorialMemo(number - 1);
8
}
9
10
void main() {
11
// Calculate the factorial of 50(1 to 50).
12
final f50 = factorialMemo(50);
13
// Calculate the factorial of 10(1 to 10).
14
// The result is retrieved from the cache,
15
// computed previously for f50.
16
final f10 = factorialMemo(10);
17
// Calculate the factorial of 100(1 to 100).
18
// First calculates the factorial from 51 to 100,
19
// then retrieves the remainder from cache, calculated by f50(1 to 50).
20
final f100 = factorialMemo(100);
21
22
print(
23
'Results:\n'
24
'\t10!: $f10\n'
25
'\t50!: $f50\n'
26
'\t100!: $f100\n'
27
);
28
}

In the above example, the factorialMemo function is called with different numbers, and the results are stored in the cache. When the same number is passed to the factorialMemo function again, the result is retrieved from the cache instead of recalculating it.