Yesterday said the string concatenation, today to say connected, I mean a bunch of non-array or collection types of content to spell a string out.
The simplest is to use the + operator, and then there are StringBuilder and StringBuffer. If it is taught in training schools, it is generally said that the preferred use of StringBuilder followed by StringBuffer, do not use + inefficient. In fact, it is enough to use + in most cases, because + is actually compiled after StringBuilder (no StringBuilder version is StringBuffer), and if 2 string constants are added, they can be merged into one in the compiler.
A scenario in which you create StringBuilder manually is to use string joins in loops with many loops, similar to this:
<pre name= "code" class= "Java" >
String result = ""; for (int i = 0; i < 1_000_000; ++i) {
In this scenario, the 4th line of code creates a new StringBuilder for Each loop execution of the For loop, which is significantly less efficient when the number of loops is greater (for example, there is an order of magnitude difference in looping 5,000 execution times on my computer). This decrease in efficiency is mainly derived from + = rather than creating StringBuilder objects, so for this:
for (int i = 0; i < 1_000_000; ++i) { String result = xxx + yyy + zzz;}
It is not necessary to create StringBuilder manually. But when the number of loops is so great that the cost of creating objects needs to be considered, it is necessary to consider manually creating a reuse within the loop outside of the loop. But this scenario for the new person should be no chance to meet, do not care about it.
[One knowledge point per day]15-java language-string connection