Поиск…


Запоминать о закрытии

Начиная с Groovy 1.8, на закрытие добавлен удобный метод memoize() :

// normal closure
def sum = { int x, int y  ->
    println "sum ${x} + ${y}"
    return x + y
}
sum(3, 4)
sum(3, 4)
// prints
// sum 3 + 4
// sum 3 + 4

// memoized closure
def sumMemoize = sum.memoize()
sumMemoize(3, 4)
// the second time the method is not called 
// and the result it's take from the previous 
// invocation cache
sumMemoize(3, 4)
// prints
// sum 3 + 4

Запоминать о методах

Начиная с Groovy 2.2 groovy.transform.Memoized аннотация добавляется к удобным методам memoize с просто добавлением аннотации @Memoized :

import groovy.transform.Memoized

class Calculator {
    int sum(int x, int y){
        println "sum ${x} + ${y}"
        return x+y
    }   
    
    @Memoized
    int sumMemoized(int x, int y){
        println "sumMemoized ${x} + ${y}"
        return x+y
    }
}

def calc = new Calculator()

// without @Memoized, sum() method is called twice
calc.sum(3,4)
calc.sum(3,4)
// prints
// sum 3 + 4
// sum 3 + 4

// with @Memoized annotation
calc.sumMemoized(3,4)
calc.sumMemoized(3,4)
// prints
// sumMemoized 3 + 4


Modified text is an extract of the original Stack Overflow Documentation
Лицензировано согласно CC BY-SA 3.0
Не связан с Stack Overflow