【发布时间】:2021-10-21 06:52:33
【问题描述】:
在我的旧项目中,此代码对 10000 个元素执行超过一分钟
private ByteArrayInputStream getInputStreamFromContactFile(MyDTO contacts) {
long start = System.currentTimeMillis();
try {
byte[] bytes = contacts.getLines()
.stream()
.map(lineItem -> lineItem.value)
.reduce(contacts.getHeader().concat("\n"), (partialString, el) -> partialString + el+ '\n')
.getBytes();
return new ByteArrayInputStream(bytes);
} finally {
log.info("Duration is {}ms", System.currentTimeMillis() - start);
}
有什么明显的方法可以让它更快吗?
【问题讨论】:
-
你基本上只是想加入
\n的行? -
这能回答你的问题吗? Java: convert List<String> to a String
-
@WJS 正如我已经提到的,这段代码是遗留代码
-
并不是指
you个人。但我想你知道每个映射/方法返回什么以及预期的最终结果。 -
返回类型是
ByteArrayInputStream还是InputStream就足够了?另一点:代码在语义上是不正确的。归约函数不是关联的,并且单位元并不是真正的单位元。 JavaStream的reduce不是左折叠。
标签: java string performance java-stream