Over a million developers have joined DZone.

Cool Stuff in Groovy 1.8: Memoization

· Java Zone

Easily build powerful user management, authentication, and authorization into your web and mobile applications. Download this Forrester report on the new landscape of Customer Identity and Access Management, brought to you in partnership with Stormpath.

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

The Java Zone is brought to you by Stormpath—offering a complete, pre-built User Management API for building web and mobile applications, and APIs. Download our new whitepaper: "Build Versus Buy: Customer Identity Management for Web and Mobile Applications".

Topics:

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

{{ parent.tldr }}

{{ parent.urlSource.name }}