Posts Tagged ‘caching

memoize() in Groovy

with 5 comments

Memoization generally means remembering the output for the already passed input.

In Groovy, memoization is performed using memoize().

An example of memoize() called on closures is given below,


def toSquare={a->

//Case 1:
println toSquare(5)           // O/P:25 --> Got after 2000ms
//Case 2:
println toSquare(5)           // O/P:25 --> Got IMMEDIATELY
//Case 3:
println toSquare(6)           // O/P:36 --> Got after 2000ms

In the above code,There is a closure toSquare.

Here any  parameter that is passed into the closure is squared only after 2000ms and above all, the closure is Memoized.

  • Case 1 : When the closure is called for the first time and parameter 5 is passed, the computation is done completely . In accordance with the computational flow, the result is printed only after 2000ms .
  • Case 2: When the closure is called for the second time and the same parameter 5 is passed, computation is not done and the result is displayed immediately. This is becuase of the memoize(). i.e., By Memoization principle , it stores the calculated value of the input that has been passed already.
  • Case 3: Here , a new input is being passed. Computation is done.Result is displayed after 2000ms. However now that , this result for this particular input will be cached.

memoize()                                     –> stores all the new inputs and the corresponding outputs.

memoizeAtLeast(minimum)  –> stores atleast a minimum number of results.

memoizeAtMost(maximum) –> stores the maximum number of results specified .


Have a memoizable day 🙂


Written by thangaveluaishwarya

September 21, 2013 at 11:25 PM