Search code examples
javastringimmutabilitystringbuilderstringbuffer

Strings are immutable - that means I should never use += and only StringBuffer?


Strings are immutable, meaning, once they have been created they cannot be changed.

So, does this mean that it would take more memory if you append things with += than if you created a StringBuffer and appended text to that?

If you use +=, you would create a new 'object' each time that has to be saved in the memory, wouldn't you?


Solution

  • Yes, you will create a new object each time with +=. That doesn't mean it's always the wrong thing to do, however. It depends whether you want that value as a string, or whether you're just going to use it to build the string up further.

    If you actually want the result of x + y as a string, then you might as well just use string concatenation. However, if you're really going to (say) loop round and append another string, and another, etc - only needing the result as a string at the very end, then StringBuffer/StringBuilder are the way to go. Indeed, looping is really where StringBuilder pays off over string concatenation - the performance difference for 5 or even 10 direct concatenations is going to be quite small, but for thousands it becomes a lot worse - basically because you get O(N2) complexity with concatenation vs O(N) complexity with StringBuilder.

    In Java 5 and above, you should basically use StringBuilder - it's unsynchronized, but that's almost always okay; it's very rare to want to share one between threads.

    I have an article on all of this which you might find useful.