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
, 在這種場景下顯然更適合用普通的循環