Memoization in Groovy

Hi Guys! I would like to share with you a very interesting concept of groovy that I learnt in the Grails Conference I attended last week. The concept is “Memoization in Groovy”. I didn’t hear about Memoization before. I found it quite interesting. So, I tried some Memoization examples on groovyConsole and thought of sharing it with you.

What is Memoization ?

Memoization is a technique that is used to store the results of function calls and returning the cached result when the same inputs occurs. It results in faster processing.

In the above example we defined a closure and assign it to func1. Now we call the the closure 4 times but we can see in the output that the body is executed only 2 times. Why ? Its because of using “.memoize()”. We passed 2 duplicate values 3 and 4. The first time we call func1(3) and func1(4) its result is stored in the cache. Next time when we again pass 3 and 4, the body is not executed at all. Instead a cached result of that function is returned.

How it can be useful ?

It can be very useful for recursive calculations like calculating factorial, fibonacci using recursion.

Fibonacci for 5
Fibonacci for 4
Fibonacci for 3
Fibonacci for 2
Fibonacci for 1
Fibonacci for 0
Fibonacci for 1
Fibonacci for 2
Fibonacci for 1
Fibonacci for 0
Fibonacci for 3
Fibonacci for 2
Fibonacci for 1
Fibonacci for 0
Fibonacci for 1

We can see many duplicate calls for values like 1,2,3 etc. in the above example.