1

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.

Altan Gokcek
  • 91
  • 2
  • 9
  • Why just don't use StringBuilder and append strings to it ? – Nikolay Tomitov Feb 25 '16 at 10:23
  • 1
    duplicate of http://stackoverflow.com/questions/1532461/stringbuilder-vs-string-concatenation-in-tostring-in-java – Edi Feb 25 '16 at 10:27
  • Possible duplicate of [StringBuilder vs String concatenation in toString() in Java](http://stackoverflow.com/questions/1532461/stringbuilder-vs-string-concatenation-in-tostring-in-java) – Joshua Goldberg Mar 08 '17 at 19:08

2 Answers2

7

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.

Petr Mensik
  • 26,874
  • 17
  • 90
  • 115
  • Actually I will create a JSON and i will not use a loop for that so i am trying to figure out if its good idea to use StringBuilder or its not necessary. – Altan Gokcek Feb 25 '16 at 10:26
  • Usually it's not needed, JVM is very good in stuff like that :) – Petr Mensik Feb 25 '16 at 10:36
  • +1, although the first sentence is incorrect: `No, Java will always convert concatenation into the StringBuilder`. In some cases the compiler leaves it as a String. ([source 1](http://stackoverflow.com/a/1532499/1682559) - comment in this answer; [source 2](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.18.1) - actual specs (quote: 'To increase the performance of repeated string concatenation, a Java compiler **may** use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.'). – Kevin Cruijssen Feb 25 '16 at 10:41
2
  • 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

Wangbo
  • 325
  • 7
  • 18