When to use Stringbuilder and Stringbuffer instead of concatenating with "+" operator in Java?

Asked

Viewed 169 times

3

What are the benefits of concatenating a string using StringBuilder or StringBuffer instead of simply using the operator +?

2 answers

3


Depends on how you use the +. If it is a simple concatenation, done all at once in a single expression, it is efficient and can use without fear, this is converted to a method that makes concatenation appropriately and quickly.

I’ve read some optimizations that even using more than one expression it can be efficient, but don’t count on it, it’s specific implementation detail.

If it is a noose where you go making several successive concatenations (usually above 4) then the result will be bad to tragic because it goes making a new allocation in memory and copy of the text to each concatenation performed, ie the cost goes growing exponentially. There you must use one of the two methods of building string in accordance with How Stringbuffer() and Stringbuilder behave()?.

The answer accepted in the question linked is too simplistic and verges on error, but it serves to see the difference between these two data structures string.

  • 1

    @Carlosheuberger really messed this up, didn’t he? So much so that it verges on error.

-1

As Maniero put it well, Stringbuilder and Stringbuffer should be used when it is necessary to perform successive concatenations. This prevents memory waste.

What I wanted to add is an observation about the decision between one and the other. Stringbuilder is faster, but Stringbuffer is thread-safe.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.