【发布时间】:2014-07-23 11:11:59
【问题描述】:
与普通 Java for 循环相比,Groovys 收集方法(关于空间(!)和时间)的性能如何?
例如对于这个用例:
- sum() 与带变量的 for 循环
- each() 与带变量的 for 循环
- inject() 与带变量的 for 循环
- collect() 与带有临时收集的 for 循环
- findAll() 与带有临时集合的 for 循环
- find() 与带变量的 for 循环
那么,考虑到这些结果,是否建议在关键环境(例如 Grails-WebApp)中使用 for 循环而不是 Groovy-collection-methods?是否有关于 Groovy/Grails 性能(优化)的资源?
使用这个 GBench 测试,我得到了以下 CPU 时间结果:
user system cpu real
forLoop 2578777 67 2578844 2629592
forEachLoop 2027941 47 2027988 2054320
groovySum 3946137 91 3946228 3958705
groovyEach 4703000 0 4703000 4703000
groovyInject 4280792 108 4280900 4352287
import groovyx.gbench.BenchmarkBuilder
def testSize = 10000
def testSet = (0..testSize) as Set
def bm = new BenchmarkBuilder().run {
'forLoop' {
def n = 0
for(int i = 0; i<testSize; i++) {
n += i
}
return n
}
'forEachLoop' {
def n = 0
for(int i in testSet) {
n += i
}
return n
}
'groovySum' {
def n = testSet.sum()
return n
}
'groovyEach' {
def n = 0
testSet.each { n + it }
return n
}
'groovyInject' {
def n = testSet.inject(0) { el, sum -> sum + el }
return n
}
}
bm.prettyPrint()
【问题讨论】:
标签: java performance grails optimization groovy