Java Groovy集合与空间/时间有关的性能注意事项
与普通Java for循环相比,Groovys收集方法(关于空间(!)和时间)的性能如何 例如,对于这个用例:Java Groovy集合与空间/时间有关的性能注意事项,java,performance,grails,optimization,groovy,Java,Performance,Grails,Optimization,Groovy,与普通Java for循环相比,Groovys收集方法(关于空间(!)和时间)的性能如何 例如,对于这个用例: sum()与带变量的for循环 each()与带有变量的for循环 inject()与带有变量的for循环 collect()与带有临时集合的for循环 findAll()与带有临时集合的for循环 find()与带有变量的for循环 因此,考虑到这些结果,在关键环境(例如Grails WebApp)中使用Groovy收集方法上的循环是否可取?是否有关于Groovy/Grails性
- sum()与带变量的for循环
- each()与带有变量的for循环
- inject()与带有变量的for循环
- collect()与带有临时集合的for循环
- findAll()与带有临时集合的for循环
- find()与带有变量的for循环
使用此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()
用户系统cpu实时
forLoop 2578777 67 2578844 2629592
forEachLoop 2027941 47 2027988 2054320
groovySum 3946137 91 3946228 3958705
groovyEach 4703000 0 4703000 4703000
GroovyInput 4280792 108 4280900 4352287
导入groovyx.gbench.BenchmarkBuilder
def testSize=10000
def testSet=(0..testSize)作为集合
def bm=新的BenchmarkBuilder()。运行{
“forLoop”{
定义n=0
对于(int i=0;i sum+el}
返回n
}
}
bm.prettyPrint()
有趣的基准测试。sum()
的速度较慢,这并不奇怪。以下是实现过程:
private static Object sum(Iterable self, Object initialValue, boolean first) {
Object result = initialValue;
Object[] param = new Object[1];
for (Object next : self) {
param[0] = next;
if (first) {
result = param[0];
first = false;
continue;
}
MetaClass metaClass = InvokerHelper.getMetaClass(result);
result = metaClass.invokeMethod(result, "plus", param);
}
return result;
}
正如您所见,它必须是通用的,并且使用元编程。其结果是更大的时间成本
您粘贴的基准测试结果清晰且具有很强的自描述性。如果您确实需要更好的性能,最好使用
进行循环。+1表示“如果您确实需要更好的性能”.Code性能不应该是开启时的主要关注点,例如,IO密集型操作或DB驱动系统。性能狂热者应该已经做好了。阿门。如果它的性能“足够好”,并且易于阅读和维护,这比速度快得多,但没有人理解它。在需要之前,不要开始朝0和1的方向前进。