-
Bug
-
Resolution: Fixed
-
P4
-
21
-
jdk-21+19-68-gbad6aa68e4d
-
b23
The implementation of `com.sun.tools.javac.util.List.map()` looks like this:
```
public <Z> List<Z> map(Function<A, Z> mapper) {
boolean changed = false;
ListBuffer<Z> buf = new ListBuffer<>();
for (A a : this) {
Z z = mapper.apply(a);
buf.append(z);
changed |= (z != a);
}
return changed ? buf.toList() : (List<Z>)this;
}
```
User Christoph Dreis noticed when profiling compilation tasks that `List.map()` is responsible for very many allocations, however, in many cases the map is empty and any associated allocation is unnecessary.
Therefore, an easy and obvious optimization here would be for `List.map()` to first check if the list is empty, and if so, avoid unnecessarily allocating a `ListBuffer`.
```
public <Z> List<Z> map(Function<A, Z> mapper) {
boolean changed = false;
ListBuffer<Z> buf = new ListBuffer<>();
for (A a : this) {
Z z = mapper.apply(a);
buf.append(z);
changed |= (z != a);
}
return changed ? buf.toList() : (List<Z>)this;
}
```
User Christoph Dreis noticed when profiling compilation tasks that `List.map()` is responsible for very many allocations, however, in many cases the map is empty and any associated allocation is unnecessary.
Therefore, an easy and obvious optimization here would be for `List.map()` to first check if the list is empty, and if so, avoid unnecessarily allocating a `ListBuffer`.