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

Build vs Buy a Data Quality Solution: Which is Best for You? Gain insights on a hybrid approach. Download white paper now!

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

Build vs Buy a Data Quality Solution: Which is Best for You? Maintaining high quality data is essential for operational efficiency, meaningful analytics and good long-term customer relationships. But, when dealing with multiple sources of data, data quality becomes complex, so you need to know when you should build a custom data quality tools effort over canned solutions. Download our whitepaper for more insights into a hybrid approach.

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}