lotus

贵有恒何必三更眠五更起 最无益只怕一日曝十日寒

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

 

常用的四种循环,普通for-增强for-forEach-forEach-Stream循环  是否真正思考过他们的不同

实践出真知,让我们从实践着手

public class ForDemo {
public static void main(String[] args) {

Integer initial = 10;

for (int n = 1; n < 6; n++) {
System.out.println("-----------------------------------------");

List<String> sourceList = new ArrayList<>();
for (int i = 0; i < initial; i++) {
sourceList.add("第" + i + "条数据");
}
compareCycle(sourceList);

initial *= 10;
sourceList = null;
}
}

public static void compareCycle(List<String> sourceList) {
System.out.println("数据条数:" + sourceList.size());
long a1 = System.currentTimeMillis();
for (int i = 0; i < sourceList.size(); i++) doSome();
long a2 = System.currentTimeMillis();
System.out.println("普通for循环用时:" + (a2 - a1) + " ms");

long b1 = System.currentTimeMillis();
for (String t : sourceList) doSome();
long b2 = System.currentTimeMillis();
System.out.println("增强for循环用时:" + (b2 - b1) + " ms");

long c1 = System.currentTimeMillis();
sourceList.forEach((t) -> doSome());
long c2 = System.currentTimeMillis();
System.out.println("forEach循环用时:" + (c2 - c1) + " ms");

long d1 = System.currentTimeMillis();
sourceList.stream().forEach((t) -> doSome());
long d2 = System.currentTimeMillis();
System.out.println("forEach-Stream循环用时:" + (d2 - d1) + " ms");

long e1 = System.currentTimeMillis();
sourceList.parallelStream().forEach((t) -> doSome());
long e2 = System.currentTimeMillis();
System.out.println("forEach-parallelStreamm循环用时:" + (e2 - e1) + " ms");
}

private static void doSome() {
try {
Thread.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
}
}

  运行结果:

-----------------------------------------
数据条数:10
普通for循环用时:13 ms
增强for循环用时:13 ms
forEach循环用时:133 ms
forEach-Stream循环用时:15 ms
forEach-parallelStreamm循环用时:5 ms
-----------------------------------------
数据条数:100
普通for循环用时:130 ms
增强for循环用时:126 ms
forEach循环用时:128 ms
forEach-Stream循环用时:126 ms
forEach-parallelStreamm循环用时:17 ms
-----------------------------------------
数据条数:1000
普通for循环用时:1262 ms
增强for循环用时:1263 ms
forEach循环用时:1263 ms
forEach-Stream循环用时:1264 ms
forEach-parallelStreamm循环用时:159 ms
-----------------------------------------
数据条数:10000
普通for循环用时:12640 ms
增强for循环用时:12617 ms
forEach循环用时:12653 ms
forEach-Stream循环用时:12636 ms
forEach-parallelStreamm循环用时:1581 ms
-----------------------------------------
数据条数:100000
普通for循环用时:126229 ms
增强for循环用时:127097 ms
forEach循环用时:126671 ms
forEach-Stream循环用时:126742 ms
forEach-parallelStreamm循环用时:15791 ms

Process finished with exit code 0

  

 

posted on 2022-06-28 16:22  白露~  阅读(239)  评论(0编辑  收藏  举报