You might know that the String concat(+) method is a costly operation compared to the StringBuffer or StringBuilder append() method. But you might not know the actual performance difference.

Let me show you the performance difference with a simple test program:

  1. package test;
  2. public class StrVsBuffVsBuild {
  3.         public static void main(String[] args) {
  4.                 int count=200000;
  5.                 System.out.println(“Number of Strings concat Operation is \'”+count+”\'”);
  6.                 long st = System.currentTimeMillis();
  7.                 String str = “”;
  8.                 for (int i = 0; i < count; i++) {
  9.                         str += “MyString”;
  10.                 }
  11.                 System.out.println(“Time taken for String concat (+) Operation is \'”+(System.currentTimeMillis()-st)+”\’ Millis”);
  12.                 st = System.currentTimeMillis();
  13.                 StringBuffer sb = new StringBuffer();
  14.                 for (int i = 0; i < count; i++) {
  15.                         sb.append(“MyString”);
  16.                 }
  17.                 System.out.println(“Time taken for StringBuffer.append() Operation is \'”+(System.currentTimeMillis()-st)+”\’ Millis”);
  18.                 st = System.currentTimeMillis();
  19.                 StringBuilder sbr = new StringBuilder();
  20.                 for (int i = 0; i < count; i++) {
  21.                         sbr.append(“MyString”);
  22.                 }
  23.                 System.out.println(“Time taken for StringBuilder.append() Operation is \'”+(System.currentTimeMillis()-st)+”\’ Millis”);
  24.         }
  25. }

Here is the output of the above test program:

Number of Strings concat Operation is ‘200000’
Time taken for String concat (+) Operation is ‘373933’ Millis
Time taken for StringBuffer.append() Operation is ’19’ Millis

Time taken for StringBuilder.append() Operation is ‘5’ Millis

The String concat (+) method took 6.2 minutes, while StringBuffer and StringBuilder append() took only 19 and 5 milliseconds, respectively. Is it comparable? Moreover, during the entire 6.2-minute execution of the String concat() operation, the Java process took 100% CPU usage. You can see the CPU usage of the m/c and Java program in the graphs below:

 

So, use StringBuilder or StringBuffer append() instead of String concat(+). Your next question might be “Which one is better, StringBuffer or StringBuilder?” Since the StringBuffer methods are synchronized, it is safe if the code is accessed by multiple threads. The StringBuilder methods are not synchronized, so it is not thread-safe. So if you need to append a global variable that can be accessed by multiple threads, you should use StringBuffer. If it is a method-level variable that cannot be accessed by multiple threads, you should use StringBuilder. Due to the absence of synchronization, StringBuilder is faster than StringBuffer.