public class TestForEach {
private static List<Integer> list = new ArrayList<Integer>();
static{
for (int i = 0; i < 1000000; i++){
list.add(i);
}
}
public static void main(String[] args) {
long stratTime = System.currentTimeMillis();
list.forEach(Integer::byteValue);
long endTime = System.currentTimeMillis();
System.out.println("stream is "+ (endTime - stratTime));
stratTime = System.currentTimeMillis();
for (Integer integer : list) {
integer.byteValue();
}
endTime = System.currentTimeMillis();
System.out.println("forEach is "+ (endTime - stratTime));
stratTime = System.currentTimeMillis();
for (int i = 0; i < list.size(); i++) {
list.get(i).byteValue();
}
endTime = System.currentTimeMillis();
System.out.println("forEach is "+ (endTime - stratTime));
}
}
测试代码如上,
10条数据:
stream is 49
forEach is 0
for(;;) is 0
100条数据:
stream is 46
forEach is 0
for(;;) is 0
1000条数据:
stream is 55
forEach is 0
for(;;) is 0
10000条数据:
stream is 55
forEach is 0
for(;;) is 0
10万条数据:
stream is 62
forEach is 16
for(;;) is 0
100万条数据:
stream is 63
forEach is 15
for(;;)is 0
1000万条数据:
stream is 62
forEach is 31
for(;;)is 16
1亿条数据:
stream is 188
forEach is 149
for(;;) is 157
10亿条数据:
10亿条数据没跑出结果来
stream().forEach用的多线程方式,其调用线程池的时候必然会耗费更多的时间。但如果你在循环内要处理的事情很多,或者要循环调用远程接口/数据库的时候,无疑极大的提升了效率。
如果是遍历进行少量操作,还是别用 stream().forEach 了
微信公众号:二虎程序