Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8306860

Avoid unnecessary allocation in List.map() when list is empty

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Fixed
    • Icon: P4 P4
    • 21
    • 21
    • tools
    • 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`.

            acobbs Archie Cobbs
            acobbs Archie Cobbs
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: