我对Java的新特性Lambda非常感兴趣。除了提供简洁清晰的代码之外,它还通过使用Stream而不是创建对象来提高性能。
我创建了一个简单的测试来创建一组随机数,然后计算其中有多少大于49。我感到惊讶的是,正则for和foreach循环提供了更好的性能。
这是我使用的代码:
long numberOfData = 20000000;
Random random = new Random();
IntStream intStream = random.ints(0, 100);
List<Integer> rand = intStream.limit(numberOfData)
.boxed()
.collect(Collectors.toList());
// Iterate using "Lambda"
OffsetTime startL = OffsetTime.now();
long countL = rand.stream()
.filter(x -> x > 49)
.count();
OffsetTime endL = OffsetTime.now();
Duration durationL = Duration.between(startL, endL);
System.out.println("[Lambda ] " + countL + " / " + numberOfData
+ " in " + durationL.toMillis() + "ms");
// Iterate using "Foreach"
int countFE = 0;
OffsetTime startFE = OffsetTime.now();
for (int aNumber : rand) {
if (aNumber > 49) {
countFE++;
}
}
OffsetTime endFE = OffsetTime.now();
Duration durationFE = Duration.between(startFE, endFE);
System.out.println("[Foreach] " + countFE + " / " + numberOfData
+ " in " + durationFE.toMillis() + "ms");
// Iterate using "For"
int countF = 0;
int maxLoop = rand.size();
OffsetTime startF = OffsetTime.now();
for (int i = 0; i < maxLoop; i++) {
if (rand.get(i) > 49) {
countF++;
}
}
OffsetTime endF = OffsetTime.now();
Duration durationF = Duration.between(startF, endF);
System.out.println("[For ] " + countF + " / " + numberOfData
+ " in " + durationF.toMillis() + "ms");
第一个运行结果:
[Lambda ] 10002783 / 20000000 in 325ms
[Foreach] 10002783 / 20000000 in 296ms
[For ] 10002783 / 20000000 in 195ms
第二次运行结果(等等类似):
[Lambda ] 10000408 / 20000000 in 330ms
[Foreach] 10000408 / 20000000 in 304ms
[For ] 10000408 / 20000000 in 202ms
注意:我使用的是运行在Eclipse露娜4.4.0forWindows上的JDK 1.8.0_11。都是32位。
我的问题是:
发布于 2014-12-30 08:32:24
我认为有两个问题: 1.编译IntPredicate花费了大量时间。解决方案声明为IntPredicate out IntPredicate predicate=x -> x> 49;long countL = rand.stream() .filter(谓词) .count();2.下一个问题是count()函数慢。但我不知道解决办法
https://stackoverflow.com/questions/25306077
复制相似问题