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并没有优势。
``