groovy Closure Memoize Methods Simple memoization


Example

def count = 0

nonmemoized = { long n -> println "nonmemoized: $n"; count++ }

nonmemoized(1)
nonmemoized(2)
nonmemoized(2)
nonmemoized(1)
assert count == 4


def mcount = 0

memoized = { long n -> println "memoized: $n"; mcount++ }.memoize()

memoized(1)
memoized(2)
memoized(2)
memoized(1)
assert mcount == 2