When using StringBuilder and StringBuffer instead of concatenating with "+" operator in Java?

3

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

asked by anonymous 01.11.2018 / 14:30

2 answers

3

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

I have read some optimization that even using more than one expression it can be efficient, but do not count on it, it's specific implementation detail.

If it is a loop where you are doing several successive concatenations (usually above 4) then the result will be bad to tragic because it will make a new memory allocation and copy of the text to each concatenation the cost is going up exponentially. You should then use one of the two string methods to StringBuffer () and StringBuffer StringBuilder ()? .

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

01.11.2018 / 14:41
0

As Maniero has put it well, StringBuilder and StringBuffer should be used when successive concatenations are required. This avoids wasting memory.

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

    
07.11.2018 / 19:21