繁体   English   中英

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

[英]Java's Lambda Stream Filter Count is Slower than For and Foreach Loop

我对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

注意:我正在使用在Windows的Eclipse Luna 4.4.0上运行的JDK 1.8.0_11。 全部都是32位。


我的问题是:

  1. 我的考试有问题吗?
  2. Lambda的数据流是否仅对涉及多个集合的操作有好处?

我认为有两个问题:1.编译IntPredicate会花费很多时间。 解决方案从过滤函数IntPredicate谓词= x-> x> 49中声明为IntPredicate; long countL = rand.stream().filter(predicate).count(); 2.下一个问题是count()函数很慢。 但我不知道解决方案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM