Lately I've been thinking about some (possible) performance improvements for StringBuffer / StringBuilder:
Now, SBs are designed to work with char-arrays, because they are mutable, and if you append a value, you don't need to create extra objects. In most use-cases, an SB will be used to concatenate some (String)values. Most people don't set the initialCapacity, because that requires some extra code. The default cap is 16. Now, let's concat some strings:
sb.append("Hello ").append("Joris"/*user.getName()*/).append(", how are you doing ").append("Today?" /* or night */);
This will do the following:
check capacity for 6 more chars
copy "Hello " chars
count = 6
check capacity for 5 more chars
copy "Hello " chars
count = 11
check capacity for 18 more chars
expand capacity: curcap*2 or newsize -> (16+1)*2 > 5+9 --> newcap = 34
copy "Hello Joris"
copy " how are you doing " chars
count = 29
check capacity for 6 more chars
expand capacity: curcap*2 or newsize -> (16+1)*2 > 34+6 --> newcap = 70
copy "Hello Joris how are you doing "
copy "Today?" chars
count = 6
Ok.. So.. how could we prevent the expanding? If we'd have set the initialCapacity to 40, that wouldn't have happened. But as I said, nobody really does that, except for high performance stuff.
If you create an SB that will keep an linked list (or arraylist and probably a custom implementation) of strings and just add the new strings to the list. You wouldn't have to do all the copying. Only when you invoke toString() (or charAt, or something similar), you will have to create a single string. But by then, you already know how large the string will be!
That way, you prevent temporary array copies, temporary char-array creations and destructions, and therefore reducing GC.
Of course, I haven't tested all this in a real life situation :) If someone has a nice testcase for String concatenation performance, please send it to me. The tests I do are biased ofcourse ^^.