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

Formatter.format might take a long time to format an integer or floating-point

XMLWordPrintable

    • b06
    • generic
    • generic
    • Verified

        ADDITIONAL SYSTEM INFORMATION :
        Any OS (tested on Ubuntu, and MacOS) and also tested on JDK8 and JDK17

        A DESCRIPTION OF THE PROBLEM :
        String.format takes tens of minutes to format a floating point if format specifies that it should be prepended with large number of 0. e.g. String.format("%09000000d", 2);

         

        STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
        The code below took 1693 seconds (28 minutes) to return a string with 9 millions of chars. Same happens for 'f' format specifier. Time spent in format seems to increase quadric with the width of the generated string.

        String s = String.format("%09000000d", 2);

        However, the code below, that use 'x' as specifier returns way faster

        String s = String.format("%09000000x", 2);


        EXPECTED VERSUS ACTUAL BEHAVIOR :
        EXPECTED -
        I expect the String.format to take similar amount of time regardless of formatter.


        ACTUAL -
        Returns correct result but very slow for 'd' and 'f' format specifier. Works as expected on for 'x' format specifier

        ---------- BEGIN SOURCE ----------
        public class SystemFormat {
            public static void main(String[] args) {
                long t1 = System.currentTimeMillis();
                String sd = String.format("%0500000d", 2);
                long t2 = System.currentTimeMillis();
                String sx = String.format("%0500000x", 2);
                long t3 = System.currentTimeMillis();
                long diff1 = t2 - t1;
                long diff2 = t3 - t2;
                System.out.format("diff1 = %d%n", diff1);
                System.out.format("diff2 = %d%n", diff2);
            }
        }

        // outputs
        // diff1 = 5927
        // diff2 = 10
        ---------- END SOURCE ----------

        CUSTOMER SUBMITTED WORKAROUND :
        do not use String.format with larger specifier and prepend it with '0'.

        FREQUENCY : always


              rgiulietti Raffaello Giulietti
              webbuggrp Webbug Group
              Votes:
              0 Vote for this issue
              Watchers:
              10 Start watching this issue

                Created:
                Updated:
                Resolved: