Altan Gokcek
Altan Gokcek

Reputation: 81

Java String vs StringBuilder

As far as i know + operator in Java String is overloaded and while we are using + operator it automatically chooses StringBuffer or StringBuilder to concatenate strings with better performance. Only exception of this is while we are using + operator inside a loop. In this case Java doesn't use benefits of StringBuffer and StringBuilder. Is that true? I will concatenate 40 Strings (around 4500 chars) and I will repeat it so often so I wanted be sure about it.

Upvotes: 0

Views: 5041

Answers (2)

Petr Mensik
Petr Mensik

Reputation: 27536

No, Java will always (almost always, see comment bellow) convert concatenation into the StringBuilder. However the problem with loop is that it will create new instance of StringBuilder per each walkthrough.

So if you do String someString = i + "something"; inside the loop which goes from 0 to 1000 it will create for you new instance of StringBuilder 1000 times. Which could be a performance problem then. So just declare StringBuilder before the loop and then use it inside it.

Upvotes: 7

4862610
4862610

Reputation: 325

  • String is immutable while StringBuilder is mutable it means when you create a String you can never change it

  • String is thread safe while StringBuilder not

  • String stores in Constant String Pool while StringBuilder in Heap

When you loop

oldString = oldString + somechars,

it means you create a new String and put oldString`s value into it first ,then append somechars ,then redirect the oldString variable to the result

Upvotes: 2

Related Questions