本文章只是對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時候要考慮多線程一些因素。