Memoization is a well known optimization technique to avoid repeated calculations. With dynamic programming languages like Groovy it is possible to extend the behaviour of an already exisiting class at runtime.
In Groovy this is accomplished with the Meta Object Protocoll and its ExpandoMetaClass. In Groovy every class has a meta class that can be changed and extended at runtime. One method of this meta class is the invokeMethod() that has the following signature.
This method controls the calls of methods in the class. By overwriting this method one can implement memoization easily.
cache contains the results of the previous calls. The set
methods contains the name of the methods that should get memoized.
Lets write a test for this class.
m0 is created before the memoization decorator was called. Therefore all the three calls to the method
f were executed. For object
m1 the method
f was called only once. Well the observant reader will have noticed, that the results of the computations are different for
m1. This is a reminder that the correctness is preserved only for purely functional methods, e. g. methods without internal state. This is not the case in our example.
Remark: This post was adapted to the new blog format in November 2016.