Java: automatic memoization Java: automatic memoization python python

Java: automatic memoization


Spring 3.1 now provides a @Cacheable annotation, which does exactly this.

As the name implies, @Cacheable is used to demarcate methods that are cacheable - that is, methods for whom the result is stored into the cache so on subsequent invocations (with the same arguments), the value in the cache is returned without having to actually execute the method.


I came across a memoization library called Tek271 which appears to use annotations to memoize functions as you describe.


I don't think there is a language native implementation of memoization.

But you can implement it easily, as a decorator of your method. You have to maintain a Map: the key of your Map is the parameter, the value the result.

Here is a simple implementation, for a one-arg method:

Map<Integer, Integer> memoizator = new HashMap<Integer, Integer>();public Integer memoizedMethod(Integer param) {    if (!memoizator.containsKey(param)) {        memoizator.put(param, method(param));    }     return memoizator.get(param);}