title: Java System.out.print efficiency
body: <p>In the last few days, doing some competitive programming exercises, I found some solutions to some problems where instead of printing out text in the console in a <code>for</code> loop, they constructed a <code>StringBuilder</code> by appending the texts after each other. First I was confused but I gave it a try and made some benchmarks. </p>
  
  <p>First Test: this is the classic way to print something on the screen:</p>
  
  <pre><code>class TestClass {
  
      public static void main(String args[]) throws Exception {
          double startTime = System.currentTimeMillis();
  
          //code
          for (int i = 0; i &lt; 1000000; i++) {
              System.out.print("test");
          }
          //code
          double endTime = System.currentTimeMillis();
          String result = String.format("for loop: %.5f", (endTime-startTime) / 1000);
          System.out.print("\n"+result);
      }
  
  }
  </code></pre>
  
  <p>Second test: and this is the enhanced version with <code>StringBuilder</code>:</p>
  
  <pre><code>class TestClass {
  
      public static void main(String args[]) throws Exception {
          double startTime = System.currentTimeMillis();
  
          //code
          StringBuilder sb = new StringBuilder();
          for (int i = 0; i &lt; 1000000; i++) {
              sb.append("test");
          }
          System.out.print(sb);
          //code
          double endTime = System.currentTimeMillis();
          String result = String.format("for loop: %.5f", (endTime - startTime) / 1000);
          System.out.print("\n" + result);
      }
  
  }
  </code></pre>
  
  <p>After running the tests several times(running them with Intel i5 6500 quad core 3.2 GHZ CPU, Win 10), the results are the following:  </p>
  
  <pre><code>first test(for loop): 4,25s  
  second test(StringBuilder): 0.23s
  </code></pre>
  
  <p>The results are not unexpected because <code>out.print</code> is synchronized so every time we call it, it will add some overhead. But being almost 20 times slower is somewhat strange. </p>
  
  <p>My question is: is there a way we can improve this further?</p>