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

Clean-up toString() methods of some primitive wrappers

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Fixed
    • Icon: P4 P4
    • 18
    • None
    • core-libs
    • None
    • b09

      AS of JDK 17 some of primitive wrappers, e.g. Long, Integer, Double and Float in their implementations of Object.toString() delegate to utility toString(primitive) methods.

      Unlike those, Boolea, Byte, Character and Short just duplicate the contents of utility methods in implementations of Object.toString().

      Yet another issue is a tiny discrepancy in implementation related to Byte and Short: (see e.g. Byte):

      public static String toString(byte b) {
          return Integer.toString((int)b, 10);
      }

      public String toString() {
          return Integer.toString((int)value);
      }

      Unlike in overriden method, In utility one they explicitly specify radix which can be skipped, as implementation of Integer.toString(int,int) has a fast-path for radix 10, ending in Integer.toString(int). This simplification gives tiny improvement, see benchmark:

      @BenchmarkMode(Mode.AverageTime)
      @OutputTimeUnit(TimeUnit.NANOSECONDS)
      @Fork(jvmArgsAppend = {"-Xms2g", "-Xmx2g"})
      public class ByteToStringBenchmark {
          @Benchmark
          public String byteToString() {
              return Byte.toString((byte) 1);
          }
      }

      Before

      Benchmark Mode Cnt Score Error Units
      ByteToStringBenchmark.byteToString avgt 30 11,648 ± 1,906 ns/op

      After

      Benchmark Mode Cnt Score Error Units
      ByteToStringBenchmark.byteToString avgt 30 10,016 ± 0,530 ns/op

            stsypanov Sergey Tsypanov
            stsypanov Sergey Tsypanov
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: