【发布时间】:2010-08-06 16:50:13
【问题描述】:
假设我正在运行以下任一代码 sn-ps 以获得 1000 个Event 条目的列表(在allEventsToAggregate 中)。如果allEventsToAggregate 中的事件按customerId 排序,每个客户大约有3 个事件,我会在第一个实现中看到性能改进吗?这本质上是字符串比较与HashMap 查找性能的问题。
选项 1:
Map<String, List<Event>> eventsByCust = new HashMap<String, List<Event>>();
List<Event> thisCustEntries;
String lastCust = null;
for (Event thisEvent : allEventsToAggregate) {
if (!thisEvent.getCustomerId().equals(lastCust)) {
thisCustEntries = eventsByCust.get(thisEvent.getCustomerId());
if (thisCustEntries == null) {
thisCustEntries = new ArrayList<Event>();
}
}
thisCustEntries.add(thisEvent);
eventsByCust.put(thisEvent.getCustomerId(), thisCustEntries);
lastCust = thisEvent.getCustomerId();
}
选项 2:
Map<String, List<Event>> eventsByCust = new HashMap<String, List<Event>>();
for (Event thisEvent : allEventsToAggregate) {
List<Event> thisCustEntries = eventsByCust.get(thisEvent.getCustomerId());
if (thisCustEntries == null) {
thisCustEntries = new ArrayList<Event>();
}
thisCustEntries.add(thisEvent);
}
【问题讨论】:
标签: java performance algorithm