I have a method that is a pure function and takes a while to run. I would like to memoize this method so that subsequent calls are much faster. I can see in Groovy's documentation that you can memoize closures via:
foo = {…}.memoize()
However, I cannot find a way to memoize a member method. Is there a way to do this?
In Groovy 2.2.X there will be a new AST transform called @Memoized
which will do this for you.
import groovy.transform.Memoized
class Woo {
@Memoized
def sum( int a, int b ) {
Thread.sleep( 1000 )
a + b
}
}
new Woo().with {
println new Date()
println sum( 1, 2 )
println new Date()
println sum( 1, 2 )
println new Date()
}
Another option would be to write some sort of AST transformation to allow you to annotate the method with @Memoize
, and have the memoization done for you.
I can find a couple of examples, one here for adding Redis as a Memoization cache to Grails, and another here which seems to allow memoization of single argument methods by basically manipulating the AST to look like the second part of epidemian's answer.
As you probably want multiple parameters, I'd go for epidemian's second method. However writing an AST transform might be an interesting experiment/side project?
It's something that if done right, I could see going back into the Groovy core source code as well (for fame and glory) :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With