On Java Development

All things related to Java development, from the perspective of a caveman.

The Immutable String and Performance

without comments


Objects of the String class are immutable. If you examine the JDK documentation for the String class, you’ll see that every method in the class that appears to modify a String actually creates and returns a brand new String object containing the modification. The original String is left untouched and memory is used to contain each string object. Over time and across multiple applications, these unused objects will come under the purview of the JVM’s garbage collection cycle which can impact performance of the application server.

StringBuilder or StringBuffer should be employed whenever the case arises calling for string concatenation using the “+” operator.

The StringBuilder Class
The Java StringBuilder class represents string objects that can be changed. No new object is created or returned. Generally use the StringBuilder class for string objects that will change.

The StringBuffer Class
StringBuffer is synchronized meaning that multiple threads can safely process StringBuffer objects. However, additional overhead is required to make StringBuffer synchronized. Since StringBuffer is slower than StringBuilder. Therefore, the StringBuffer class for string objects that will be changed by multiple threads of execution.

When to use one over the other
Choosing the wrong string class can cause undesirable results. For example, you can easily append the letter X to a String object: String s = s + “X”. But this concatenation operation inside a loop is inefficient. That is because the String class happens to create a StringBuilder (or StringBuffer) object to do the concatenation work. Creating this object every time is costly.

A better choice for this example is the StringBuilder class. For example, we can simply append the letter X to the StringBuilder object: sbd.append(‘X’). This is much faster than the previous example. In sample testing (200,000 iterations), the previous example took almost one minute to complete while StringBuilder took less than a second.

If you add a requirement for multiple threads, then StringBuffer becomes the better choice. But in sample testing (one million iterations), StringBuffer was five times slower than StringBuilder. However StringBuffer guarantees thread safety, whereas StringBuilder does not. In other words, you can get unpredictable results when using StringBuilder objects in multithreaded programs.

Written by admin

March 28th, 2014 at 7:19 am

Posted in Java Strings

Leave a Reply

You must be logged in to post a comment.