gpt4 book ai didi

Java 的 Lambda 流过滤器计数比 For 和 Foreach 循环慢

转载 作者:行者123 更新时间:2023-11-29 08:46:02 25 4
gpt4 key购买 nike

我对 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 Luna 4.4.0 for Windows 上运行的 JDK 1.8.0_11。都是 32 位的。


我的问题是:

  1. 我的考试有错吗?
  2. Lambda 的流是否只对涉及多个集合的操作有好处?

最佳答案

我认为有两个问题:1. 编译IntPredicate 耗费大量时间。解决方案被声明为 IntPredicate out of filter function IntPredicate 谓词=x -> x > 49;长 countL = rand.stream() .filter(谓词) 。数数();2. 下一个问题是 count() 函数很慢。但我不知道解决方案

关于Java 的 Lambda 流过滤器计数比 For 和 Foreach 循环慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25306077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com