2

in Jack Shirazi book "Java Performance Tuning", he presents a way to optimize conversion from double to String. the code of the optimization can be found here: http://onjava.com/onjava/2000/12/15/graphics/DoubleToString.java

however, there seem to be some issue with specific numbers for a 2 digits display, when using the method with 0.0951 (until 0.0999) it returns "0.0a", which is obviously incorrect. when running it with 0.0949, it correctly returns 0.09. when running it with 1.0951 it correctly return 1.10.

any idea about what's wrong ? I'm trying to understand the small bits, but haven't found the culprit yet.

here's my test main:

public DoubleToString() {
double d1 = 0.0949;
double d2 = 0.0951;

StringBuffer sb = new StringBuffer();

sb.append("display d1 = ");
appendFormatted(sb, d1, 2, '.', ',', 3, '-', '-');
sb.append(" : ");
appendFormatted(sb, d2, 2, '.', ',', 3, '-', '-');

System.out.println(sb.toString());
}
Bastien
  • 1,539
  • 2
  • 10
  • 18

1 Answers1

0

Strong suggestion:

  1. Create a benchmark that does 100,000 or a million double-to-string conversions in a loop.

  2. Get the timing for using "appendFormatted()"

  3. Compare the timing for using the standard Java DecimalFormat (as of Java 1.4, 2002) or printf Formatter (as of Java 5, 2004)

  4. Consider that this article was written back in 2000 ... and many of the "optimizations" he talks about are undoubtedly completely obsolete with respect to current JDK's and JVM's.

IMHO...

paulsm4
  • 99,714
  • 15
  • 125
  • 160
  • 1
    Interesting comment. I did just that, and the results imply Shirazi's method is still much faster than both DecimalFormat & Formatter. looped 10,000,000: appendFormatted = 5.3s, DecimalFormat = 31.3s, Formatter = 63.2s – Bastien Aug 08 '11 at 05:18
  • @Bastien I used the same class for one of my projects and didn’t notice the problem you faced. It’s returning expected results compared to DecimalFormatter. Although it breaks for something that’s 15 digits long in my test. Perhaps in your case the problem could be from the JVM version you are using. How did you solve the problem statement eventually. I must say that Jack’s implementation is still the fastest in comparison with OpenJdk 11 that I am at. – Anand Nadar Jun 05 '20 at 14:59