直接调用或通过call()方法调用
def adder = {x, y -> return x+y}
assert adder(2, 3) == 5
assert adder.call(4, 5) == 9
def benchmark(repeat, Closure worker) {
def start = System.currentTimeMillis()
repeat.times{worker(it)}
def stop = System.currentTimeMillis()
return stop - start
}
def slow = benchmark(10000) {(int) it/2}
def fast = benchmark(10000) {it.intdiv(2)}
println slow
println fast
assert slow > fast
通过闭包实现累加
def foo(n) {
return {n += it}
}
def closure = foo(1)
assert closure(2) == 3
assert closure(1) == 4
本文探讨了利用闭包进行函数调用优化的方法,包括直接调用和使用call()方法,同时展示了如何通过闭包实现累加操作,并对比了不同方式的性能表现。

被折叠的 条评论
为什么被折叠?



