zl程序教程

您现在的位置是:首页 >  前端

当前栏目

lamda中stream的forEach与for循环对比

循环 for 对比 stream foreach lamda
2023-06-13 09:15:10 时间

大家好,又见面了,我是你们的朋友全栈君

对比方式

  • 将一个字符串数组进行输出的方式:
  • 代码
public static void main(String[] args) throws IOException { 

int n=500000;
String[] strings = new String[n];
Long streamStart = System.currentTimeMillis();
Arrays.stream(strings).forEach(System.out::println);
Long streamEnd = System.currentTimeMillis();
for (int i = 0; i < n; i++) { 

System.out.println();
}
Long forEnd = System.currentTimeMillis();
System.out.println("stream forEach 运行时间:" + (streamEnd - streamStart));
System.out.println("for循环 运行时间:" + (forEnd - streamEnd));
}

  • 数据运行表格

数组长度

for循环(ms)

stream的forEach(ms)

100

1

31

1000

6

52

5000

22

62

10000

33

89

20000

75

168

50000

249

276

80000

534

432

100000

696

454

500000

904

2704

1000000

1740

3616

  • 截图(按照表格截图)

1000000

500000

总结

循环大概在50000大小的时候for循环就开始慢慢运行时间大于forEach,在50000数据之前都是for循环优势。但是当我直接加到1000000大小时发现for循环的速度优势又回来了,又测试了500000发现依然是for循环优势。 所以大概率下,几万几万数据时forEach速度是领先的。小数据和极大数据下for循环领先,所以推荐使用for循环,一般业务中很少有几万数据去循环。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/234403.html原文链接:https://javaforall.cn