本文章只是对jdk新增的stream(),parallelStream()效率和for(),forEach()效率进行对比。
测试环境:
- Mac 8核16g下环境测试
- JDK版本:1.8.0_221
- IDEA2019.2.2
测试代码
public static void main(String[] args) throws Exception{
List<String> stringList=new ArrayList<>();
for (int i=0;i<10;i++){
stringList.add("第"+i+"条数据");
}
System.out.println("一共"+stringList.size());
//for循环
long forNowTime=System.currentTimeMillis();
for (int i=0;i<stringList.size();i++){
TestMethod();
}
long forTime=System.currentTimeMillis();
System.out.println("for循环需要时间"+(forTime-forNowTime));
//增强for循环
long forsNowTime=System.currentTimeMillis();
for(String s:stringList){
TestMethod();
}
long forsTime=System.currentTimeMillis();
System.out.println("增强for循环需要时间"+(forsTime-forsNowTime));
//forEach循环
long forEachNowTime=System.currentTimeMillis();
stringList.forEach(s -> TestMethod());
long forEachTime=System.currentTimeMillis();
System.out.println("forEach循环需要时间"+(forEachTime-forEachNowTime));
//Stream
long StreamNowTime=System.currentTimeMillis();
stringList.stream().forEach(s -> TestMethod());
long StreamTime=System.currentTimeMillis();
System.out.println("Stream需要时间"+(StreamTime-StreamNowTime));
//parallelStream
long parallelStreamNowTime=System.currentTimeMillis();
stringList.parallelStream().forEach(s -> TestMethod());
long parallelStreamTime=System.currentTimeMillis();
System.out.println("Stream需要时间"+(parallelStreamTime-parallelStreamNowTime));
}
private static void TestMethod() {
try {
Thread.sleep(1);
}catch (Exception e){
e.printStackTrace();
}
}
循环10次结果
一共数据为10
for循环需要时间12
增强for循环需要时间12
forEach循环需要时间57
Stream需要时间13
Stream需要时间5
循环1000次结果
for循环需要时间1252
增强for循环需要时间1282
forEach循环需要时间1311
Stream需要时间1253
Stream需要时间87
循环100000次结果
一共数据为100000
for循环需要时间128615
增强for循环需要时间129780
forEach循环需要时间126431
Stream需要时间128558
parallelStream需要时间8038
结论:
从单纯的数据来看,前面三个并没有很明显的区别,可能都是串行的原因,但是明显感觉stream效率要比for要低那么一点单,但是并行的速度明显区别其他三个(主要是多线程的原因),希望在用到paralleStream时候要考虑多线程一些因素。