Search

Dark theme | Light theme

November 19, 2013

Groovy Goodness: Cache Methods Invocations with Memoize Annotation

In Groovy we can cache closure results with memoization. In Groovy 2.2 a new @Memoize AST transformation is added, which can be used to cache plain method results. We apply the annotation to our method and the result of the method is cached if the method is invoked for the first time. If we invoke the method a second time with the same arguments then the cached result is returned.

In the following sample we want to cache the method increment(int). We use a script variable incrementChange to show when a cached method invocation takes place or a non-cached one.

import groovy.transform.*

// Script variable which is changed when increment()
// method is invoked. 
// If cached method call is invoked then the value
// of this variable will not change.
@Field boolean incrementChange = false

@Memoized 
int increment(int value) {
    incrementChange = true
    value + 1 
}

// Invoke increment with argument 10.
increment(10)

// increment is invoked so incrementChange is true.
assert incrementChange

// Set incrementChange back to false.
incrementChange = false

// Invoke increment with argument 10.
increment(10)

// Now the cached method is used and
// incrementChange is not changed.
assert !incrementChange

// Invoke increment with other argument value.
increment(11)

// increment is invoked so incrementChange is true.
assert incrementChange