大家好,又见面了,我是你们的朋友全栈君
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