MyArchiBook

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,

Example:

def toSquare={a->
  sleep(2000)
  a*a
}.memoize()

//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 🙂

Advertisements

Written by thangaveluaishwarya

September 21, 2013 at 11:25 PM

5 Responses

Subscribe to comments with RSS.

  1. precise and I didn’t know this. thank you for sharing.

    steve

    September 22, 2013 at 10:45 AM

  2. u always surprise me with super stuff

    Ravi

    September 22, 2013 at 7:37 PM

  3. very good blogs. wating for more

    beatit_001@gmail.com

    September 27, 2013 at 10:46 AM

  4. You are gifted and can see that in your writings.

    tom

    September 28, 2013 at 7:08 PM

  5. This is a topic that’s close to my heart…
    Cheers! Where aree your contact details though?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: