Java tips String concatenations using StringBuffer

Java provides StringBuffer and String. Always use StringBuffer when you want concatenate string. StringBuffer has better performance over String when doing simple string concatenation.

String is immutable, that something cannot be changed. When you concatenate using String, JVM actually create new Object for each concatenation. Create new Object is expensive. See below example.

When using String, you may doing something like:

String message = ""; // new object
message = message + "I am "; // another new
message = message + "25"; // another new
message = message + " years old"; // another new

When using StringBuffer, you will doing something like

StringBuffer sb = new StringBuffer(); // new object here
sb.append("I am ");
sb.append("25");
sb.append(" years old");
String message = sb.toString(); // another new

As you can see, by using String, you create a bunch of new objects. When you have more things to concatenate, more and more objects created, and again, creating new object is very expensive, and make application performance worse.

It is strongly recommended by using StringBuffer to append string, and at the last, call toString() to export the string content into String object, then you can use it for any purpose.

So for the example on Java tips on joining string with separator, the code can be changed to below:

private static String join_1(String[] array, String separator) {
	StringBuffer sb = new StringBuffer();
	String comma = "";
	for(int i = 0; i < array.length; i++) {
		sb.append(comma + array[i]);
		comma = separator;
	}
	return sb.toString();
}

private static String join_2(String[] array, String separator) {
        StringBuffer sb = new StringBuffer();
	for(int i = 0; i < array.length; i++) {
		sb.append(array[i] + separator);
	}
        String s = sb.toString();
	return s.substring(0, s.length() - separator.length());
}

Another note, when use String for concatenation, internally it will create StringBuffer to do actual concatenation. Refer this link for more information.

Author: fyhao

Jebsen & Jessen Comms Singapore INTI University College Bsc (Hon) of Computer Science, Coventry University

Leave a Reply