In many cases, StringBuilder is faster and faster than string concatenation.
The fact is that StringBuilder is faster than string because the intermediate object is generated during string concatenation and eventually garbage is generated.
For example:
String str = "";
Str + = "B ";
Str + = "c ";
The final result is "abc", but the second line produces "AB", which is only an intermediate object and garbage. Using StringBuilder will avoid the generation of such intermediate objects.
What if I write this?
String str = ""
+ "B"
+ "C ";
Will this be slower than StringBuilder? Absolutely not!
Not to mention that string concatenation of such constants will be processed during compilation. Even if "B" and "c" are not constants or variables, the compilation result is also string. concat (...), no intermediate object is generated.
Of course, multiple statements are converted into one statement. The disadvantage is that debugging is not so convenient.
Not all times can be easily converted to concatenation, for example, in the case of if, while, and other statement blocks.
The purpose of StringBuilder is to avoid generating intermediate variables, but if so:
Stringbuilder. Append ("a" + str1 + "B"), an intermediate variable is generated: "a" + str1 + "B", which should be changed
Stringbuilder. Append ("a"). Append (str1). Append ("B"). The performance is better, but the readability is almost the same.
My conclusion:It can be converted into a string concatenation StringBuilder operation, which is better to use concatenation. But try to reduce + =.