title: A faster alternative to DecimalFormat.format()?
body: <p>In order to improve its performance, I have been profiling one of my applications with the VisualVM sampler, using the  minimum sampling period of 20ms. According to the profiler, the main thread spends almost a quarter of its CPU time in the <a href="http://docs.oracle.com/javase/6/docs/api/java/text/NumberFormat.html#format%28double%29"><code>DecimalFormat.format()</code></a> method.</p>
  
  <p>I am using <code>DecimalFormat.format()</code> with the <code>0.000000</code> pattern to "convert" <code>double</code> numbers to a string representation with exactly six decimal digits. I know that this method is relatively expensive and it <em>is</em> called a lot of times, but I was still somewhat surprised by these results.</p>
  
  <ol>
  <li><p>To what degree are the results of such a sampling profiler accurate? How would I go about verifying them - preferrably without resorting to an instrumenting profiler?</p></li>
  <li><p>Is there a faster alternative to <code>DecimalFormat</code> for my use case? Would it make sense to roll out my own <code>NumberFormat</code> subclass?</p></li>
  </ol>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>I created a micro-benchmark to compare the performance of the following three methods:</p>
  
  <ul>
  <li><p><code>DecimalFormat.format()</code>: Single <code>DecimalFormat</code> object reused multiple times.</p></li>
  <li><p><code>String.format()</code>: Multiple independent calls. Internally this method boils down to</p>
  
  <pre><code>public static String format(String format, Object ... args) {
      return new Formatter().format(format, args).toString();
  }
  </code></pre>
  
  <p>Therefore I expected its performance to be very similar to <code>Formatter.format()</code>.</p></li>
  <li><p><code>Formatter.format()</code>: Single <code>Formatter</code> object reused multiple times.</p>
  
  <p>This method is slightly awkward - <code>Formatter</code> objects created with the default constructor append all strings created by the <code>format()</code> method to an internal <code>StringBuilder</code> object, which is not properly accessible and therefore cannot be cleared. As a consequence, multiple calls to <code>format()</code> will create a <em>concatenation</em> of all resulting strings.</p>
  
  <p>To work around this issue, I provided my own <code>StringBuilder</code> instance that I cleared before use with a <code>setLength(0)</code> call.</p></li>
  </ul>
  
  <p>The results where interesting:</p>
  
  <ul>
  <li><code>DecimalFormat.format()</code> was the baseline at 1.4us per call.</li>
  <li><code>String.format()</code> was slower by a factor of two at 2.7us per call.</li>
  <li><code>Formatter.format()</code> was also slower by a factor of two at 2.5us per call.</li>
  </ul>
  
  <p>Right now it looks that <code>DecimalFormat.format()</code> is still the fastest among these alternatives.</p>