@Documented @Retention(value=SOURCE) @Target(value=METHOD) public @interface Memoized
Example usage:
class MemoizedExample {
@Memoized
int sum(int n1, int n2) {
println "$n1 + $n2 = ${n1 + n2}"
n1 + n2
}
}
which becomes (approximately):
class MemoizedExample {
private final Closure memoizedSum = { int n1, int n2 ->
private$method$memoizedSum(n1,n2)
}.memoize()
int sum(int n1, int n2) {
memoizedSum(n1, n2)
}
private private$method$memoizedSum(int n1, int n2) {
println "$n1 + $n2 = ${n1 + n2}"
n1 + n2
}
}
Upon execution of this code:
def instance = new MemoizedExample() println instance.sum(1, 2) println instance.sum(1, 2) println instance.sum(2, 3) println instance.sum(2, 3)The following will be output:
1 + 2 = 3 3 3 2 + 3 = 5 5 5
More examples:
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
Modifier and Type | Optional Element and Description |
---|---|
int |
maxCacheSize
The maximum size the cache can grow to.
|
int |
protectedCacheSize
Number of cached return values to protect from garbage collection.
|