Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringBuilder append vs +

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?

like image 513
Michael Avatar asked Oct 25 '11 09:10

Michael


People also ask

Why is StringBuilder better than string concatenation?

Reason being : The String concatenate will create a new string object each time (As String is immutable object) , so it will create 3 objects. With String builder only one object will created[StringBuilder is mutable] and the further string gets appended to it.

What is the difference between appending a string to a StringBuilder and concatenating two strings with a operator?

Performance wise difference between + operator and StringBuilder. append is, + has a very small overhead of instantiating StringBuilder instance and converting result back to String object. This will reflect in the performance graph above.

What can I use instead of StringBuilder?

Objects of String are immutable, and objects of StringBuffer and StringBuilder are mutable. StringBuffer and StringBuilder are similar, but StringBuilder is faster and preferred over StringBuffer for the single-threaded program. If thread safety is needed, then StringBuffer is used.

Is StringBuilder still necessary?

Fortunately, you don't need to use StringBuilder anymore - the compiler can handle it for you. String concatenation has always been a well-discussed topic among Java developers. It's been costly.


1 Answers

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.

like image 144
NPE Avatar answered Oct 19 '22 18:10

NPE