This question already has an answer here:
What is the benefit and trade-off of using a string builder over pure string concatenation?
new StringBuilder(32).append(str1)
.append(" test: ")
.append(val)
.append(" is changed")
.toString();
vs say
str1 + " test: " + val + " is changed".
str1
is a random 10 character string.
str2
is a random 8 character string.
In your trivial example, none because the compiler uses
StringBuilder
to do String concatenation. If the concatenation occurred in a loop, however, the compiler could create severalStringBuilder
andString
objects. For example:Each time line 3 above is executed, a
StringBuilder
object is created, the contents ofs
appended, "a" appended, and then theStringBuilder
is converted into a String to be assigned back tos
. A total of 10StringBuilder
s and 10String
s.Conversely, in
Only 1
StringBuilder
and 1String
are created.The main reason for this is that the compiler could not be smart enough to understand that the first loop is equivalent to the second and generate more efficient (byte) code. In more complex cases, it's impossible even for the smartest compiler to know. If you absolutely need this optimization, you have to introduce it manually by using
StringBuilder
s explicitly.The quick answer is the performance: when you are using native String classes it operates immutable strings, which means when you are writing
it will create two strings "java" and " is awesome", than create a new third string "java is awesome" from previous two ("java" and "is awesome") which later are likely to be deleted by a garbage collector (because they are no more used in app). That is a slow solution.
More faster solution is an appliance of StringBuffer class which through the smart algorightms that provide a buffer (that is obvious from its name) for merging strings and as a result would not remove the initial string during the concatenation process.
In case you are writing single thread-application (no concurrancy issues during which multiple threads access same object) it is better to apply StringBuilder which has even faster performance than the initial StringBuffer class.