Improving performance with StringBuilder
Let’s say we have a String content
and we want to concatenated a String line
to it.
Nothing more natural than doing:
Or simply
It works! Simple and obvious. However, Java Strings are immutable. It means that every re-assignment above creates a new instance of String on memory with the content of the previous string plus the concatenated one.
This simple solution works, but what if the String is used within a loop to concatenate hundred/thousand lines from a buffer?
The implementation above can impact the performance as a new instance is created for every new line of text.
So, a solution could be to use a StringBuilder
instead:
StringBuilder
is mutable, so it can be changed without new instantiation.
That’s it!!