High Java CPU due to String Concatenation – String + Vs StringBuffer or StringBuilder

Many of you might know, the String concat(+) is costly operation compare to 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. System.out.println(“Time taken for String concat (+) Operation is ‘”+(System.currentTimeMillis()-st)+”‘ Millis”);
  11. st = System.currentTimeMillis();
  12. StringBuffer sb = new StringBuffer();
  13. for (int i = 0; i < count; i++)
  14. sb.append(“MyString”);
  15. System.out.println(“Time taken for StringBuffer.append() Operation is ‘”+(System.currentTimeMillis()-st)+”‘ Millis”);
  16. st = System.currentTimeMillis();
  17. StringBuilder sbr = new StringBuilder();
  18. for (int i = 0; i < count; i++)
  19. sbr.append(“MyString”);
  20. System.out.println(“Time taken for StringBuilder.append() Operation is ‘”+(System.currentTimeMillis()-st)+”‘ Millis”);
  21. }
  22. }

Following are 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 (+) took 6.2 Minutes, however others took only 19 / 5 milliseconds.
Is it comparable ? Moreover, during the execution of String concat()
operation time(6.2 Minutes), the java process took 100% CPU
utilization. You can see the CPU usage of the m/c and java program in the below graphs,

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

– Ramesh

You Can Learn More About the ManageEngine Product Line By Going to www.ManageEngine.ca

The original article/video can be found at High Java CPU due to String Concatenation – String + Vs StringBuffer or StringBuilder

About the Author: Shannon Lewis

Leave a Reply Cancel reply