测试 for foreach stream 性能

Posted sanmubird

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了测试 for foreach stream 性能相关的知识,希望对你有一定的参考价值。

 1 import com.google.common.collect.Lists;
 2 import org.junit.Test;
 3 
 4 import java.util.List;
 5 import java.util.stream.Collectors;
 6 
 7 /**
 8  *
 9  */
10 public class Demo {
11 
12     @Test
13     public void test() throws InterruptedException {
14 //        int size = 5000000;
15         int size = 50000000;
16 
17         Thread.sleep(1000);
18 
19         long t1s = System.currentTimeMillis();
20         List<Integer> list1 = Lists.newArrayListWithExpectedSize(size);
21         for (int i = 0; i < size; i++) {
22             list1.add(i + 1);
23         }
24         long t1e = System.currentTimeMillis();
25         System.out.println("for 循环 耗时:" + (t1e - t1s) + " , size = " + list1.size());
26 
27 
28         long t2s = System.currentTimeMillis();
29         List<Integer> list2 = Lists.newArrayListWithExpectedSize(size);
30         list1.forEach(
31                 i -> list2.add(i + 1)
32         );
33         long t2e = System.currentTimeMillis();
34         System.out.println("foreach  耗时:" + (t2e - t2s) + " , size = " + list2.size());
35 
36 
37         long t3s = System.currentTimeMillis();
38         List<Integer> list3 = list1.stream().map(i -> i + 1).collect(Collectors.toList());
39         long t3e = System.currentTimeMillis();
40         System.out.println("stream  耗时:" + (t3e - t3s) + " , size = " + list3.size());
41 
42         Thread.sleep(1000);
43     }
44 
45 
46 }

测试结果:

技术图片

 

 

 

技术图片

 

 

技术图片

 

 

技术图片

 

 

技术图片

 

 

技术图片

以上是关于测试 for foreach stream 性能的主要内容,如果未能解决你的问题,请参考以下文章

Java集合遍历方式(for循环与stream()&forEach())比较

php中的for 和foreach性能对比

c# for和foreach哪个执行效率

.NET 中的性能分析

for-forEach-stream三种遍历方法执行效率比较与选用思考

Part of defining a topology is specifying for each bolt which streams it should receive as input(示例代