0

Am trying to append multiple strings in StringBuilder,
is there any major difference using

String str1 = "some";
String str2 = "string";

Now,

sb.append(str1).append(str2); // using chained appends

and using

sb.append(str1 + str2); // using '+' operator

My IDE suggests me to use the first method, is there difference between them regarding being thread safe or something like that?

Siva Rahul
  • 253
  • 1
  • 13
  • The reason to use `StringBuilder` is to avoid the overhead of string concatenation of many unknown (i.e. non-literal) strings (e.g. in a loop). Though note that concatenation of string literals occurs, I believe, at compile time (so using `StringBuilder` in that case would be worse). – Slaw Mar 09 '20 at 06:06
  • @Slaw so do i have to use string concatenation than using string builder – Siva Rahul Mar 09 '20 at 06:10
  • 1
    Based solely on your example code, you should be doing `sb.append("somestring")`. – Slaw Mar 09 '20 at 06:11
  • @Slaw np, ive used these as an example, i'll be appending something from variables , I've edited the question – Siva Rahul Mar 09 '20 at 06:13
  • 1
    Does this answer your question? [Yet again on string append vs concat vs +](https://stackoverflow.com/questions/8962482/yet-again-on-string-append-vs-concat-vs) – Md Golam Rahman Tushar Mar 09 '20 at 06:19
  • if you already have a `StringBuilder` use separate `append` calls; otherwise use `+` - Exception to this rule, if the strings are constants (compile time), then use `+` – user85421 Mar 09 '20 at 07:52
  • 1
    Pls take into account that starting from Java 9 the performance of string concatenation was significantly improved (JEP 280) and it might be more sensible to use it instead of playing with `StringBuilder` – fyrkov Mar 09 '20 at 08:15

3 Answers3

0

Under the hood, the Compiler replaces String concatenation with StringBuilder.append, but there are limits. Inside of loops, it creates a new StringBuilder for every iteration, calls toString and appends it to the outside StringBuilder. The same goes for method calls as it needs a value for the method call. After compilation your second version would read

sb.append(new StringBuilder().append(str1).append(str2).toString);

which is obviously not optimal, whereas the first version remains unchanged.

Nicktar
  • 5,548
  • 1
  • 28
  • 43
0

Your first method will not create any object except for already created 3 objects. However, second approach will unnecessarily first crate another object for string (str1 + str2) and then append to your StringBuilder object.

First approach is better than second approach.

P Mittal
  • 172
  • 6
0

The point of using StringBuilder is to avoid creating unnecessary String objects. String in Java is unmodifiable, which means every time you concatenate two Strings third one is created. For example following code

String concatenation = str1 + str2 + str3;

results in creating unnecessary String str1 + str2, to which then str3 is added and their result is being assigned to "concatenation".

StringBuilder allows you to put all the String you want to concatenate, without creating intermediate objects. Then when you are ready, you build final result.

You should use StringBuilder if you concatenate multiple Strings in a loop. If you want to concatenate just few Strings, you shouldn't use StringBuilder, as cost of it's creation is bigger than cost of intermediate Strings. By writing something like this

sb.append(str1 + str2);

you are obviously missing the point of StringBuilder. Either you do it only for these two Strings, which means you unnecessary create StringBuilder object or you do it in a loop, which means you unnecessary create intermediate str1 + str2 objects.

  • 1
    Actually the compiler is smart enough to transform the `str1 + str2 + str3` into `new StringBuilder().append(str1).append(str2).append(str3)`. So actually there aren't additional intermediate strings created. The second one will, indeed, lead to an additional creation of a `StringBuilder` due to the string concat. – M. Deinum Mar 09 '20 at 07:19
  • 1
    with new Java version (>= 9 ?) even the intermediate `StringBulder` is not used - compiler uses `StringConcatFactory` to create a synthetic method for concatenation – user85421 Mar 09 '20 at 07:49