What are the differences between String.concat(), StringBuffer.append(), and the '+' operator (applied to Strings)?

Alessandro A. Garbagnati

They all do basically the same thing, except that they do it in a different way and with different performances. Basically String.concat() and "+" concatenates two strings, while StringBuffer.append() appends a string to a StringBuffer.

The great difference is that String is an immutable object, while StringBuffer is not. This means that every time you assign a value to a String concatenating many Strings, you are recreating a new String every time, while, using a StringBuffer you are appending the additional String to the buffer.

If you want to have 'fun', just try these two pieces of code and see the result:

String s = new String();
long start = System.currentTimeMillis();
for (int i=0; i<10000; i++) {
  s += "a"; // or s = s.concat("a");
long stop = System.currentTimeMillis();
System.out.println("String = " + (stop-start) + "ms.");

StringBuffer sb = new StringBuffer();
start = System.currentTimeMillis();
for (int i=0; i<10000; i++) {
stop = System.currentTimeMillis();
System.out.println("StringBuffer = " + (stop-start) + "ms.");
0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact