【发布时间】:2011-09-27 14:27:38
【问题描述】:
在使用不同的排序算法时,我很惊讶 Groovy 闭包的性能非常差。到目前为止我还没有找到一个好的答案,所以现在试试我的运气;)为什么 Groovy 闭包比传统方法慢这么多?
这是一个显示性能差异的简单示例。它创建两个带有随机数的列表,并以相反的顺序对它们进行排序,测量排序时间。在我的机器上,对于 10k 个元素,使用闭包需要 270ms,而使用 Comparator 实现只需要 50ms。
时间会根据随机数的分布而有所不同。我还尝试了 Groovy 1.7.4 和 1.8.0,发现后者的性能稍好一些。但整体情况保持不变:闭包表现不佳。
我可以做些什么来提高关闭性能?当然,除了不使用闭包;) 如果性能很重要,我是否遗漏了什么或者不应该在 groovy 中使用闭包?
def numberCount = 10000
def random = new Random()
def unorderedList1 = (1..numberCount).collect{random.nextInt()}
def unorderedList2 = (1..numberCount).collect{random.nextInt()}
def timeit = {String message, Closure cl->
def startTime = System.currentTimeMillis()
cl()
def deltaTime = System.currentTimeMillis() - startTime
println "$message: \ttime: $deltaTime"
}
timeit("compare using closure") {
def comparator= [ compare: { a,b -> return b <=> a }] as Comparator
unorderedList1.sort(comparator)
}
timeit("compare using method") {
Comparator comparator = new MyComparator()
unorderedList2.sort(comparator)
}
class MyComparator implements Comparator {
int compare(a, b) {return b <=> a}
}
【问题讨论】:
-
270ms v 50ms 对我来说并不属于差异的“数量级”。如果你想看看 Groovy 的一些巧妙使用,它最终比 Java 或 C++ 实现更快(不是作为诱饵:先看视频),看这里:infoq.com/presentations/Groovy-Best-Practices
标签: performance groovy closures