For循环,Stream迭代,parallelStream()迭代的性能比较

For循环,Stream迭代,parallelStream()迭代的性能比较如下:

代码:

package com.test;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

public class StreamTest {
    public static void main(String[] args) throws IOException {
        //for 效率测试
        long from = System.currentTimeMillis();
        String contents = new String(Files.readAllBytes(
                Paths.get("E:\\zfibs\\owms-api\\src\\main\\java\\com\\zfibs\\owms\\utils\\test.txt")), StandardCharsets.UTF_8);
        String[] words = contents.split("\\PL+");
        long count = 0;
        for (String w : words) {
            if (w.length() > 5) {
                count++;
            }
        }
        long to = System.currentTimeMillis();
        System.out.println("163M 的TXT文件,用for循环的方式, 次数: " + count);
        System.out.println("耗时 : " + (to - from) + " ms");

        //stream 效率测试
        from = System.currentTimeMillis();
        String contents1 = new String(Files.readAllBytes(
                Paths.get("E:\\zfibs\\owms-api\\src\\main\\java\\com\\zfibs\\owms\\utils\\test1.txt")), StandardCharsets.UTF_8);
        List<String> words1 = Arrays.asList(contents.split("\\PL+"));
        count = words1.stream().filter(w -> w.length() > 5).count();
        to = System.currentTimeMillis();
        System.out.println("163M 的TXT文件,用stream().filter()的方式, 次数: " + count);
        System.out.println("耗时 : " + (to - from) + " ms");

        //parallelStream 效率测试
        from = System.currentTimeMillis();
        String contents2 = new String(Files.readAllBytes(
                Paths.get("E:\\zfibs\\owms-api\\src\\main\\java\\com\\zfibs\\owms\\utils\\test2.txt")), StandardCharsets.UTF_8);
        List<String> words2 = Arrays.asList(contents.split("\\PL+"));
        count = words2.parallelStream().filter(w -> w.length() > 5).count();
        to = System.currentTimeMillis();
        System.out.println("163M 的TXT文件,用sparallelStream().filter()的方式, 次数: " + count);
        System.out.println("耗时 : " + (to - from) + " ms");
    }
}

测试结果:

第一次:
在这里插入图片描述
第二次:
在这里插入图片描述
第三次:
在这里插入图片描述
从这个来看,当数据量大时,parallelStream并没有优势。
``

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值