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

Support optimizations for always-true and always-false Predicates

    Details

    • Type: Enhancement
    • Status: Resolved
    • Priority: P5
    • Resolution: Won't Fix
    • Affects Version/s: 8, 9
    • Fix Version/s: None
    • Component/s: core-libs
    • Labels:
      None

      Description

      Many Predicate-related operations, like Stream.filter and Collection.removeIf, could be optimized if they knew upfront that the Predicate was always true or always false. O(n) operations become O(1). In order to do so, though, there needs to be a way to identify these Predicates.

      Possibilities:
      - A well-known constant Predicate.TRUE, tested with ==.
      - A Predicate.true() method that always returns the same object, like Collections.emptyList, again tested with ==.
      - A default method Predicate.isTrue (returns false), accompanied by one of the above that overrides the method.

      (And similar for false.)

      Part 2 of the RFE is to optimize Stream.filter (at least), so that filter(TRUE) is a no-op and filter(FALSE) returns an empty Stream. The handling of TRUE allows downstream consumers to see the properties of the original Stream (e.g., if it is SIZED).

      A typical use case for this is to implement a method that supports some sort of filtering, but doesn't require it. Then Predicate.TRUE can act as the "default" (provided by the client or an overload) if no filtering is needed. Workaround is to implement the method twice or check some sort of sentinel (null, a flag) that indicates whether filtering should happen.

      public void doComplicatedThing() { doComplicatedThing(Predicate.TRUE); }
      public void doComplicatedThing(Predicate<? super Foo> filter) { ... someStream.filter(filter). ... }

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                psandoz Paul Sandoz
                Reporter:
                dlsmith Dan Smith
              • Votes:
                0 Vote for this issue
                Watchers:
                5 Start watching this issue

                Dates

                • Created:
                  Updated:
                  Resolved: