header

Groovy Memoized

Memoized is useful when you need to create a cache for the results of the execution of the annotated method. Therefore it can be used anywhere you need to store previously calculated data based on specific input.

In order to review how it is working, let’s review this piece of code to compute Fibonacci sequence. Basically it is characterized by the fact that every number after the first two is the sum of the two preceding ones:

 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 ...

Groovy Implementation

Integer fibonacci(Integer number){
  if(number < 2){
    return 1
  }
  fibonacci(number - 1) + fibonacci(number - 2)
}

Long start = new Date().getTime()
println fibonacci(30)
Long end = new Date().getTime()

println (end - start)

This piece of code will return as output:

1346269
242

So the time to coumpute Fibonacci from 30 took 242 milliseconds. The reason being that the computer is doing a lot of redundant work. If we add @Memoized annotation we can use cache to store calculated values and avoid this redudant work.

Fibonacci Implementation using @Memoized Annotation

import groovy.transform.Memoized

@Memoized
Integer fibonacci(Integer number){
  if(number < 2){
    return 1
  }
  fibonacci(number - 1) + fibonacci(number - 2)
}

Long start = new Date().getTime()
println fibonacci(30)
Long end = new Date().getTime()

println (end - start)

Output

1346269
63

That’s it, with that optimization we reduce 70% time doing this computation. For more information about @Memoized please go to the official Groovy site: Here

Return to the main article

comments powered by Disqus