【发布时间】:2019-07-03 08:00:17
【问题描述】:
我想通过将我的操作合并为一个来减少开销,但似乎不太清楚如何在没有错误的情况下完成我的代码
目前我有这个工作的代码:
public Map<String, Invoice> initialize(List<String> paths) {
List<Invoice> invoices = paths
.stream()
.map(Invoice::new)
.collect(Collectors.toList());
invoices
.forEach(e -> {
e.setInvoiceInputStream(reader(e.getInvoicePath()));
e.setInvoiceId(invoiceFinder.getInvoiceId(e.getInvoiceInputStream()));
});
Map<String, Invoice> invoiceMap = invoices
.stream()
.collect(
Collectors.toMap(
e -> e.getInvoiceId(),
e -> e)
);
return invoiceMap;
但是,执行此代码 3 次似乎是在浪费时间。 如果我尝试一些不同的东西,比如我得到错误:
return invoicePaths
.stream()
.map(Invoice::new)
.collect(
Collectors.collectingAndThen(
Collectors.toList(), list -> {
list
.forEach(e -> {
e.setInvoiceInputStream(reader(e.getInvoicePath()));
e.setInvoiceId(invoiceFinder.getInvoiceId(e.getInvoiceInputStream()));
});
Invoice 类中的构造函数:
public Invoice(String invoicePath) {
this.invoicePath = invoicePath;
}
如何通过优化代码来减少开销?
【问题讨论】:
-
“但是,执行此代码 3 次似乎是在浪费时间。”您是否对此进行了基准测试以确认它实际上是一个问题?需要多长时间,有多少条路径?
-
这个问题更适合codereview.stackexchange.com
-
你有没有想过改变你的数据模型而不是方法?创建一个部分初始化的
Invoice(需要以某种方式从额外服务中检索其 Id)并存储一个外部创建的 InputStream 看起来很奇怪。 -
@sfiss 你的怀疑是对的。它指出了更可疑的事情,显然
InputStream(或者实际上是Reader)被视为对象的属性,而操作看起来像是在使用它。