Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Cool Stuff in Groovy 1.8: Memoization

DZone's Guide to

Cool Stuff in Groovy 1.8: Memoization

· Java Zone ·
Free Resource

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

Groovy 1.8 has been released recently. It’s really amazing how much the team achieved in this release. Though my favorites are new AST transformations, enhanced DSL support and embedded GPars there are a few very nice methods that were added to closures.

Look at this chunk of code:

def fib = null
fib = {
    it <= 1 ? it : (fib(it - 1) + fib(it - 2))
}

long b = System.currentTimeMillis()
fib(35G)
long a = System.currentTimeMillis()

println “${(a-b) / 1000} seconds” // about 8 seconds on my machine

It takes so long as we have to calculate the same values again and again. It would be much faster if we stored already calculated values in memory. This technique is called memoization. Groovy 1.8 adds memoize method that does exactly that.

def fib = null
fib = {
    it <= 1 ? it : (fib(it - 1) + fib(it - 2))
}.memoize()

long b = System.currentTimeMillis()
fib(35G)
long a = System.currentTimeMillis()
println “${(a-b) / 1000} seconds” // about 0.08 seconds on my machine

You can apply memoize to every closure that doesn’t have side effects. You may say that this method is just a minor enhancement. Yes, you’d be right, but, in my view, such small features are what makes working with Groovy so enjoyable.

 

From http://victorsavkin.com/post/5174604204/cool-stuff-in-groovy-1-8-memoization

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}