Java 8流在读取文件和查找字数方面比通常的循环花费了更多的时间



我只是在尝试使用LinenumberReader进行文件解析的传统方式来比较Java 8流的性能。令我惊讶的是,遗留代码比Streams快得多。两者的解析逻辑相同。知道为什么会这样吗?

下面是两种方法,一种用于流,另一种用于常规Filereader/Linenumberreader。

private static void streamWalkthrough(Stream<String> lines) {
long startTime=new Date().getTime();
AtomicLong atomicLong=new AtomicLong();
lines.map(eachLine-> {
return eachLine.split(" ");
}).forEach(lineArray->{
Long occurenceOnEachLine=Arrays.stream(lineArray).filter(eachWord->{
if(eachWord.trim().equalsIgnoreCase("Kafka")) {
return true;
}
return false;
}).count();
if(occurenceOnEachLine>0) {
long existingLongValue=atomicLong.get();
atomicLong.set(existingLongValue+occurenceOnEachLine);
}
});
System.out.println("Stream code took : "+(new Date().getTime()-startTime));
}
private static void legacyWalkthrough() {
try {
LineNumberReader reader=new LineNumberReader(new FileReader(path));
String line="";
int wordCount=0;
long startTime=new Date().getTime();
while((line=reader.readLine())!=null) {
String str[]=line.split(" ");
for (String word : str) {
if(word.trim().equalsIgnoreCase("kafka")) {
wordCount++;
}
}
}
System.out.println("Legacy code took : "+(new Date().getTime()-startTime));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

根据@Rono的建议,下面的代码对我有效。它比通常的Readers更高效。。

lines.map(l->l.split(" ")). flatMap(Arrays::stream). filter(w->w.trim().equalsIgnoreCase("kafka")). count();

最新更新