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

时间:2014-08-14 10:41:03

标签: java performance loops filter lambda

我对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 个答案:

答案 0 :(得分:0)

我认为有两个问题: 1.它耗费了大量时间来编译IntPredicate。解决方案是从过滤函数中声明IntPredicate  IntPredicate谓词= x - &gt; x> 49; long countL = rand.stream()                     .filter(谓词)                     。计数(); 2.接下来的问题是count()函数很慢。但我不知道解决方案