When should you explicitly use a StringBuilder? [duplicate]

安稳与你 提交于 2019-12-04 22:28:24
Jon Skeet

It's more general than "inside loops" - it's any time you want to do concatenation over multiple statements, and don't need the intermediate result as a string. For example:

StringBuilder builder = new StringBuilder("Start");
if (someCondition) {
    builder.append("Foo");
}
if (someOtherCondition) {
    builder.append("Bar");
}
builder.append("End");
String result = builder.toString();

While you could write that as:

String result = "Start" + (someCondition ? "Foo" : "")
    + (someOtherCondition ? "Bar" : "") + "End";

... that becomes hard to read. And if there are more statements within the if bodies, it may not even be feasible.

To correct something within your question though:

As I understand it, when I do String baz = "foo" + "bar" + "123" the java compiler internally replaces the expression with a StringBuilder.

No, when you write that expression the compiler recognizes that it's a compile-time constant, and replaces it with

String baz = "foobar123";

That's a very good reason not to explicitly use a StringBuilder - the code above is clearly more efficient at execution time than

String baz = new StringBuilder("foo").append("bar").append("123").toString();

When it isn't a compile-time constant, the Java compiler will perform the concatenation using a StringBuilder, usually leaving you with easier-to-understand code than with the explicit use of StringBuilder, but with no performance hit. I suspect your teacher either doesn't properly understand string concatenation, or simply read somewhere else that you should use StringBuilder without fully understanding when it's appropriate.

Obi Wan has said that only Sith thinks in absolutes or something similar...

It's good you know that Java compiler internally replaces "+" on Strings with the usage of the StringBuilder. This is what are the compilers for: to make the life easier.

Unless you have loops, as in linked case, or conditionals from Jon Skeet's example, it's primarily the matter of readibility and the ease of maintanance.

Replacing

return "User " + userName + " said";

with

new StringBuilder().append("User ").append(userName).append(" said").toString();

makes the code longer, probably harder to modify, is more likely to force line breaks, and gives you more performance.

However, when the addition apply not only to the strings, but there are numbers involved, probably the solution with StringBuilder sometimes may be more readable.

return "User" + a + b + " said: " + (c + d);

may be more confusing as:

return new StringBuilder().append("User ").append(a).append(b)
  .append(" said: ").append(c+d).toString();  

But it's primarily the matter of opinion and coding style. "Should" is not a good word here.

They're also good for implementing things like C#'s 'out' keyword with a String. Example

public int getInt(StringBuilder error)
{
    int retVal = 0;

    if (someErrorOccured)
        error.append("Couldn't get int because of...");
    else
        retVal = whatItsSupposedToBe;

    return retVal;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!