I used to often see discussions about Java string splicing and other aspects on the Internet. I saw some Java developers in their suggestions to novice programmers like the following:
Do not use the + sign to splice strings, use the append() method of StringBuffer or StringBuilder to splice strings.
However, it is really so annoying to splice strings with + signs. Is there nothing good about using + signs to splice strings?
By looking up some content about the String class in the Java API documentation, we can see the following snippet:
"The Java language provides special support for string concatenation symbols ("+") and converting other objects into strings. String concatenation is implemented through the StringBuilder (or StringBuffer) class and its append method. String conversion is implemented through the toString method, which is defined by the Object class and can be inherited by all classes in Java."
This passage clearly tells us that in Java, using + sign splicing strings is actually implemented by StringBuffer or StringBuilder and its append method.
In addition to the Java API documentation, we can also use the tool to view the bytecode command of the class file to get the above answer. For example code:
public static void main(String[] args) { String a = "Hello"; String b = " world"; String str = a + b + " !"; System.out.println(str);} The command to view the corresponding bytecode through the tool is as follows:
From the bytecode command, we can clearly see that the following code we wrote
String str = a + b + " !";
It was converted into a statement similar to the following:
String str = new StringBuilder(String.valueOf(a)).append(b).append(" !").toString();Not only that, the Java compiler is also a relatively smart compiler. When the + sign splicing is all string literals, the Java compiler will intelligently convert it into a complete string during compilation. For example:
public static void main(String[] args) { String str = "Hello" + " world" + ", Java!"; System.out.println(str);} The Java compiler directly splices this kind of string that is all literal and converts it into a complete string when compiled.
Even if there are variables in the string spliced with + sign, the Java compiler will merge the front string literals into one string.
public static void main(String[] args) { String java = ", Java!"; String str = "Hello" + " world" + java; System.out.println(str);}From the above, it can be seen that for an operation like String str = str1 + str2 + str3 + str4, there is no problem with splicing multiple strings at one time.
In Java, String objects are immutable (Immutable). In the code, you can create multiple aliases for a certain String object. But the references of these aliases are the same.
For example, s1 and s2 are alias for "droidyue.com" objects, and the alias are stored in references to the real object. So s1 = s2
String s1 = "droidyue.com";String s2 = s1;System.out.println("s1 and s2 has the same reference =" + (s1 == s2));And in Java, the only overloaded operator is related to string splicing. +,+=. Besides that, Java designers do not allow overloading other operators.
In Java, the only overloaded operator is related to string splicing. +,+=. Besides that, Java designers do not allow overloading other operators.
As we all know, before Java 1.4, string stitching could be used to splice strings. Starting from Java 1.5, we can use StringBuilder to splice strings. The main difference between StringBuffer and StringBuilder is that StringBuffer is thread-safe and is suitable for multi-threaded operation of strings; StringBuilder is thread-safe and is suitable for operating strings under a single thread. However, most of our string stitching operations are performed under a single thread, so using StringBuilder is beneficial for performance.
Before Java 1.4, the compiler used StringBuffer to handle strings with + sign spliced strings; starting from Java 1.5, the compiler used StringBuilder to handle strings with + sign spliced strings in most cases.
When we write code in the JDK 1.4 environment, it is recommended that the + sign be used to deal with the above situation where multiple strings are spliced at once. In this way, when JDK is upgraded to 1.5 and above, the compiler will automatically convert it to StringBuilder to splice strings, thereby improving the efficiency of string splicing.
Of course, the recommended use of + sign splicing strings is only limited to using when splicing multiple strings in a statement. If you splice a string in multiple statements, it is still recommended to use StringBuffer or StringBuilder. For example:
public static void main(String[] args) { String java = ", Java!"; String str = ""; str += "Hello"; str += "world"; str += java; System.out.println(str);} The compiled byte commands of the compiler are as follows:
From the picture above, we can know that each + sign splicing statement creates a new StringBuilder object. This situation is particularly evident under cycle conditions, resulting in relatively large performance losses. Therefore, it is highly recommended to use StringBuffer or StringBuilder to handle strings in multiple statements.
About the optimization brought by using StringBuilder
In addition, when using StringBuffer or StringBuilder, we can also use the following method to further improve performance (the following code takes StringBuilder as an example, StringBuffer is similar to this).
1. Predict the maximum length of the final obtained string.
The default length of the char array inside StringBuilder is 16. When we append the string and exceed this length, StringBuilder will expand the internal array capacity to meet the needs. In this process, StringBuilder creates a new, larger capacity char array and copy the data from the original array into the new array. If we can roughly predict the maximum length of the string that is finally spliced, we can specify the initial capacity of the appropriate size when creating the StringBuilder object. For example, we need to splice to get a string containing 100 letters a. You can write the following code:
StringBuilder sb = new StringBuilder(100); for (int i = 0; i < 100; i++) { sb.append('a');}System.out.println(sb);Please balance according to actual conditions to create a StringBuilder suitable for the initial capacity.
2. For individual characters, use the char type instead of the String type as much as possible.
Sometimes, we need to append a single character after the string (for example: a), and we should use it as much as possible at this time.
sb.append('a');Instead of using:
sb.append("a");