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

Optional.toString() is unnecessarily expensive

XMLWordPrintable

    • b28

        This is Optional.toString() https://github.com/openjdk/jdk/blob/0699220830a457959b784b35af125b70f43fa3b0/src/java.base/share/classes/java/util/Optional.java#L454

            /**
             * Returns a non-empty string representation of this {@code Optional}
             * suitable for debugging. The exact presentation format is unspecified and
             * may vary between implementations and versions.
             *
             * @implSpec
             * If a value is present the result must include its string representation
             * in the result. Empty and present {@code Optional}s must be unambiguously
             * differentiable.
             *
             * @return the string representation of this instance
             */
            @Override
            public String toString() {
                return value != null
                    ? String.format("Optional[%s]", value)
                    : "Optional.empty";
            }

        String.format is surprisingly expensive, and we are seeing Optional.toString() showing up as a measurable fraction of CPU time in Google's servers. This code could just as easily use string concatenation, which would certainly be cheaper.

        Similar remarks apply to the other Optional* classes like OptionalInt, though they are used much less.

              emcmanus Eamonn McManus
              emcmanus Eamonn McManus
              Votes:
              0 Vote for this issue
              Watchers:
              5 Start watching this issue

                Created:
                Updated:
                Resolved: