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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With