Directory
The usual string concatenation method written in the preceding
It 's written in front .
This is a very basic article that will show you how to use Java to correctly and efficiently stitch strings.
These issues are also the basis of our attention to the performance optimization techniques. the normal string concatenation method uses the '+' operator to connect strings
Usually we are in the development of the general is directly to the stitching string.
String newstring = "Hello" + "world"; Hello World
The '+' operator represents the addition of the contents of a two-character variable, which is joined together. But this operation is very inefficient, and in the example above there are only two strings that do not feel a performance problem. But if you're connecting dozens of or more strings, you know why this operator can affect performance. In the 51st of Effecti Java (second edition), it is stated explicitly that the use of string concatenation operators for the concatenation of n strings requires the time of N squared. Because the string type in Java is the type of string that is designed as immutable and does not support dynamic expansion, so n strings are concatenated together, their contents are copied, so you need the time of n squared. Using the StringBuilder connection string
In order to solve the above square-level time problem, we can use Java provided StringBuilder to stitching strings, this article does not discuss multithreading, so will not go to compare the difference between StringBuilder and StringBuffer, in fact, simply said, StringBuffer design is thread-safe, suitable for multithreading use, more relevant knowledge can refer to other articles. Of course, the number of strings is not much, you can directly use '+' stitching, but note that even if stitching 3 strings requires 9 copies of the operation, so recommend more than 2 can consider StringBuilder. The time required for StringBuilder operations is linearly increased because the call to the Stringbuilder.append method does not copy all of the strings.