Memoizacja

Jest to forma „cachowania” wywołań funckji/metod. Jest szczególnie przydatna, jeśli wywołania funkcji/metod zajmują dużo czasu.

Przykład implementacji (zaciągnięty z https://dzone.com/articles/java-8-automatic-memoization)

public class Memoizer<T, U> {

  private final Map<T, U> cache = new ConcurrentHashMap<>();

  private Memoizer() {}

  public static <T, U> Function<T, U> memoize(final Function<T, U> function) {
    return new Memoizer<T, U>().doMemoize(function);
  }

  private Function<T, U> doMemoize(final Function<T, U> function) {
    return input -> cache.computeIfAbsent(input, function::apply);
  }

}

Przykładowe użycie

Function<String, String> toUpperCase = Memoizer.memoize(String::toUpperCase);
toUpperCase.apply("test"); // -> "TEST"

Jest to trywialny przykład wykorzystania, ale pokazuje działanie klasy Memoizer. Normalnie powinno się „memoizować” tylko funkcje/metody, które „pochłaniają” duże ilości zasobów.

Wersja w TypeScript

class Memoizer<T,U> {

    private cache: Map<T, U> = new Map();

    private constructor(){}

    static memoize(func: Function): Function {
        return new Memoizer().doMemoize(func);
    }
    
    private doMemoize(func: Function): Function {
        return input => {
            if(this.cache.has(input)){
                return this.cache.get(input);
            } else {
                let result = func(input);
                this.cache.set(input, result);
                return result;
            }
        }
    }
     
}

function test(text: string){
    return text.toUpperCase();
}

let memoizedTest = Memoizer.memoize(test);

memoizedTest("test");

Warto zajrzeć

1. https://dzone.com/articles/java-8-automatic-memoization
2. https://en.wikipedia.org/wiki/Memoization