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

  @Memoized
  def power2(a) {
    timesCalculated++
    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.


This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow