Wednesday, July 18, 2012

Performance of Appending Java Strings: "+" vs StringBuffer vs StringBuilder

There are quiet a few ways to append two Strings in java.

The most popular way to append two Strings in Java is, using the "+" operator. This is one of the costliest and inefficient operation. String objects are immutable, i.e., the contents of String objects cannot be altered. So, whenever a "+" operator is used to append two Strings, a new String with size = len(String1) + len(String2) is allocated and then the String1 and String2 are copied into the new String.

To fine tune String operations in Java applications "StringBuilder" and "Stringbuffer" classes can be used. StringBuilder is suitable for single threaded applications. StringBuffer is suitable for multithreaded applications.

The performance comparison between String appending using "+", StringBuffer and StringBuilder are shown in following graphs.



Time taken to append 100000 characters:
  • String Append using "+": ~40000 ms = 40 sec
  • String Append using StringBuffer: ~15 ms = 1/4 sec
  • String Append using StringBuilder: ~6 ms = 1/10 sec

No comments:

Post a Comment