steam 循环 和 foreach 循环简单对比
说明:
测试结果只表明再这种场景下使用普通的foreach
更合理, 并不是steam
流比较逊色,steam
默认使用多线程实现了, 理论上有更高的天花板, 后续有时间再详解下steam
相关的东西
运行环境
- cpu: i5-8400(6c 6t 3.8主频)
- 内存: 16G(2666频率)*2
- 系统: Mac OS 10.14.6 (18G95)
- java环境: jdk1.8.0_171
数据大小
- entries: size=11
- tableCodeList: size = 8
- 循环次数: 3000000
关键源码
int times = 3000000;
long s1 = System.currentTimeMillis();
while (times > 0) {
times--;
// 过滤掉不在显示范围内的contrast
for (Map.Entry<String, EvaluationReportVo.ContrastVo> entry : entries) {
String key = entry.getKey();
if (tableCodeList != null && tableCodeList.contains(key)) {
newContrastVoMap.put(key, entry.getValue());
}
}
}
log.info("普通循环流时间 {}ms", System.currentTimeMillis() - s1);
times = 3000000;
s1 = System.currentTimeMillis();
while (times > 0) {
times--;
Map<String, EvaluationReportVo.ContrastVo>
collect = contrastVoMap.entrySet().stream()
.filter((f) -> tableCodeList.contains(f.getKey()))
.collect(Collectors.toMap((e) -> (String) e.getKey(), (e) -> e.getValue()));
}
log.info("stream流时间 {}ms", System.currentTimeMillis() - s1);
结果
执行时间
资源消耗
- 第1行为
Memory
- 第2行为
GC 活动
- 第3行为
Class数量
- 第4行为
线程
- 第5行为
Cpu
可以看到使用普通循环内存是稳步增长的, 而使用stream
时cpu
使用率相当, 但内存增长比较迅速, 并且触发了4次GC
, 在这种场景下显然更适合用普通的循环