Why is String preferable to StringBuilder in concatenation?
Asked Answered
J

1

6

My method below needs to return a String concatenated from strings.

StringBuilder sb = new StringBuilder();
sb.append("count: ").append(this.count()).append( "\n");

return sb.toString();

In IntelliJ, the Code Inspection suggests me to replace this StringBuilder with a String like below:

String sb = "count: " + this.count() + "\n";
return sb

My impression is that StringBuilder should be used with the append method, to replace string concatenation with the plus sign. Does this code inspection suggestion make sense in IntelliJ?

Johannesburg answered 4/10, 2017 at 21:25 Comment(2)
Possible duplicate of StringBuilder vs String concatenation in toString() in JavaOutfoot
Literally just googled the title...Outfoot
T
7

You are correct in your presumptions that most IntelliJ inspections encourage you to do things in a "better" way.

However, this is not always the case. Especially where some inspections work "both ways" -> you'll have to exercise your own judgement about what is "better".

In this case, if you start with a normal concatenated string:

    return "count: " + count + "\n";

There are a few inspections available - put cursor on "count: " and hit alt-enter:

  1. Replace '+' with String.format()
  2. Replace '+' with StringBuilder.append()
  3. Replace '+' with java.text.MessageFormat.format()

If you choose option (2), you get this:

    return new StringBuilder().append("count: ").append(count).append("\n").toString();

Now, you can use alt-enter again to choose "Replace StringBuilder with String" reverse the change.

In this case, you have discovered an inspection / refactoring that is bi-directional: it works both ways. Other refactorings (such as "Encapsulate") work only one way.

As for what is "better" - you have to weigh up the performance of StringBuilder versus readability and simplicity, and make that judgement yourself - IntelliJ is just providing handy inspections to assist you ;)

Tufthunter answered 5/10, 2017 at 7:27 Comment(4)
+1 for side stepping the question headline (which is addressed in numerous other places :) and instead addressing this aspect of it: "Does this code inspection suggestion make sense ...?" very neatly.Bioscope
@glitch except it does not really answer the question because it does not explain when StringBuilder should be used, which is the reason why OP is confused.Outfoot
Aldo the description of the inspection in IntelliJ clearly says "Using a String concatenation makes the code shorter and simpler. This inspection only reports when the resulting concatenation is at least as efficient or more efficient than the original StringBuffer or StringBuilder code. "Outfoot
@Outfoot the performance implications are explained for example here: #1532961Tufthunter

© 2022 - 2024 — McMap. All rights reserved.