Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memoizing Member Methods in Groovy

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?

like image 411
mfollett Avatar asked Dec 27 '22 03:12

mfollett


1 Answers

Edit:

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()
}

Original answer

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) :-)

like image 101
tim_yates Avatar answered Feb 17 '23 18:02

tim_yates