Reputation: 350
I have a nested loop in the code below which I'm trying to optimize as I know nested for loop is very expensive, anyone has a different way to achieve this?
Thanks in advance!
private List<Map<String, Object>> updateSomething(List<Map<String, Object>> list)
throws MetadataException {
for (Map<String, Object> map : list) {
setFilePathAndOffsetParams(map);
for (Map.Entry<String, String> entry : anotherMap.entrySet()) {
updateKeyOnMap(map, entry.getKey(), entry.getValue());
}
}
return list;
}
private void updateKeyOnMap(Map<String, Object> map, String newKey, String oldKey) {
if (!newKey.equals(oldKey)) {
map.put(newKey, map.get(oldKey));
map.remove(oldKey);
}
Upvotes: 2
Views: 7735
Reputation: 181734
I have a nested loop in the code below which I'm trying to optimize as I know nested for loop is very expensive, anyone has a different way to achieve this?
Whether a loop nest is expensive depends on how many iterations of each loop are performed, and on what work is done in each iteration -- especially for the innermost loop. It is not useful to focus on eliminating nested loops in general as a mechanism for improving performance, because a restructuring that simply distributes the work differently does not usually have a significant impact. Only if by reorganizing you can arrange to eliminate unnecessary work or to increase concurrency does such a reorganization make sense.
It is unclear whether either of those alternatives applies to your case, but your best bet for improving concurrency would be to process the list elements in parallel. This is unsafe if the list may contain duplicate elements, among other possibilities, but if it is reasonable, then you might write it like this:
list.parallelStream()
.forEach(map -> {
setFilePathAndOffsetParams(map);
for (Map.Entry<String, String> entry : anotherMap.entrySet()) {
updateKeyOnMap(map, entry.getKey(), entry.getValue());
}
});
Note well, however, that whereas parallelization may improve elapsed time, it adds a bit of overhead without reducing the total amount of work. Therefore, it does not improve aggregate CPU time.
Upvotes: 5