首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Java的Lambda流过滤器计数比For和Foreach循环慢

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

Stack Overflow用户
提问于 2014-08-14 10:41:02
回答 1查看 2.3K关注 0票数 2

我对Java的新特性Lambda非常感兴趣。除了提供简洁清晰的代码之外,它还通过使用Stream而不是创建对象来提高性能。

我创建了一个简单的测试来创建一组随机数,然后计算其中有多少大于49。我感到惊讶的是,正则for和foreach循环提供了更好的性能。

这是我使用的代码:

代码语言:javascript
运行
复制
    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");

第一个运行结果:

代码语言:javascript
运行
复制
[Lambda ] 10002783 / 20000000 in 325ms
[Foreach] 10002783 / 20000000 in 296ms
[For    ] 10002783 / 20000000 in 195ms

第二次运行结果(等等类似):

代码语言:javascript
运行
复制
[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位。

我的问题是:

  1. 我的考试有什么问题吗?
  2. Lambda的流只为涉及许多集合的操作提供好处吗?
EN

Stack Overflow用户

发布于 2014-12-30 08:32:24

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

票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25306077

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档