19

What is the difference between these two lines?

stringBuilder.append("Text " + counter + " more text");
stringBuilder.append("Text ").append(counter).append(" more text");

Assuming that counter is an incrementing int, does the first line create a String "Text 0 more text", "Text 1 more text", etc. each time it's called, while the second line creates only these two Strings once: "Text " and " more text"? Is this correct?

5 Answers 5

22

In a nutshell, yes, except that the same string literals for "Text " and " more text" get reused every time.

The second variant is more efficient, since it writes each of the three components directly into the StringBuilder.

In contrast, the first variant creates another -- unnamed -- StringBuilder, writes the three components into it, calls its toString() method and writes the result into the named stringBuilder.

In summary, the first variant creates an extra StringBuilder object and an extra String object, and copies the string data twice more than the second variant.

3

Yes this is (mostly) correct.

In fact, the second doesn't create new strings at all, because it reuses the same strings each time. It will use interned versions of the "Text " and " more text" strings.

The first will create a string for "Text 1 more text" then "Text 2 more text", using a StringBuilder generated by the compiler.

0
2

It is almost correct.

I'd say more. Since java string caches all hard coded strings the instance of strings "Text " and " more text" are not created on each iteration.

2

That depends on whether Java interns the Strings or not, but it's still inefficient.

Strings are immutable, so, if you use .append("String" + something + "String"), you force Java to create a bunch of new Strings so it can end up with the final String to add to the buffer. This is an often-missed memory hog, and I've seen significant improvements in memory usage in web applications by eliminating this type of code.

1

Yes, your interpretation is (almost) correct.

The first line always creates a String object like "Text 0 more text", while the second does not create such a String object.

The second line doesn't create *any* String objects at all "Text " and " more text" are String literals that don't get re-created each time that line is executed. They are only created once.

The effect on stringBuilder is exactly the same in both cases, however.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.