2

A question just cropped into my mind that if StringBuilder/StringBuffer is always better than String then why do we still use it?

I mean shouldn't StringBuilder/StringBuffer always be used, replacing String completely? It is said "If the Object value is not going to change use String Class because a String object is immutable" but we can also use StringBuilder/StringBuffer and get better performance.

5
  • 1
    How does StringBuilder offer better performance for a string that does not change? Commented Apr 15, 2015 at 5:23
  • The fact that String contents are guaranteed immutable allows for better performance (avoid copies, safe asynchronous processing, deduplicate backing arrays, internalize String instances, cache calculation results, etc) Commented Apr 15, 2015 at 5:26
  • if we change the string like concat it then stringbuilder will give better performance. I eamnt all jobs done by String can be done by Stringbuilder/StringBuffer then why still use it? Can you explain your 2nd comment? Commented Apr 15, 2015 at 5:34
  • 1
    Add the language tag, java or ? Commented Apr 15, 2015 at 5:35
  • Don't use it when using it would make your code wrong - which is a lot of the time. Don't use it when using it would make your code harder to understand and your code is already fast enough - which is almost 100% of the time. Commented Apr 15, 2015 at 5:58

1 Answer 1

6

A String offers more functionalities than a StringBuilder. The sole purpose of a StringBuilder, as its name implies, is to build a String.

A String is not less efficient than a StringBuilder (don't know where you got that). It is actually much more efficient, because since it's immutable, you can sefely share references without needing defensive copies.

And most importantly: performance is usually not the main concern anyway. What matters more is correctness, readability, safety, maintainability. And using an immutable String increases all these factors.

If String is so much better than a StringBuilder, then why do we have a StringBuilder? Because there is one use-case where using a StringBuilder is much more efficient than using a String: constructing a String by repeatedly appending parts:

String s = "";
for (String part: collection) {
    s += part;
}

The above code is slow because many temporary String objects are created and copied, and must then be GCed. In that case, use a StringBuilder:

StringBuilder builder = new StringBuilder();
for (String part: collection) {
    builder.append(part);
}
String s = builder.toString();
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.