groovy Memoized Functions Memoized functions


Memoizing is basically a way to cache method results. This can be useful when a method is often called with the same arguments and the calculation of the result takes time, therefore increasing performance.

Starting from Groovy 2.2, methods can be annoted with the @Memoized annotation.

Imagine the following class:

class MemoDemo {
  def timesCalculated = 0

  def power2(a) {
    a * a

Now upon the first call of this method with a number it hasnt been called with before, the method will be executed:

assert power2(2) == 4
assert timesCalculated == 1

However, if we call it again with the same argument:

assert power2(2) == 4
assert timesCalculated == 1

timesCalculated has remained unchanged, yet the method returned the same result. However, calling it with a different argument:

assert power2(3) == 9
assert timesCalculated == 2

results in the body of the method being called again.