[Java Performance] Notes for String concatenation, performance concatenation
String Concatenation)
// Before Compiler optimization, String answer = integerPart + ". "+ mantissa; // String answer = new StringBuilder (integerPart) after Compiler optimization ). append (". "). append (mantissa ). toString ();
Because the compiler will optimize the concatenation of strings, the use of String concatenation in the same statement has no negative impact on the performance. It is necessary for the compiler to use StringBuilder to replace the "+" operator in any scenario for String concatenation.
However, when String concatenation is completed by multiple statements (or loops), the problem arises:
// Before Compiler optimization, String answer = integerPart; answer ++ = ". "; answer + = mantissa; // String answer = new StringBuilder (integerPart) after Compiler optimization ). toString (); answer = new StringBuilder (answer ). append (". "). toString (); answer = new StringBuilder (answer ). append (mantissa ). toString ();
In the Code optimized by the compiler, the String object in the middle and the StringBuilder object are not actually needed. In this case, you can combine the preceding statement into one. Or use the StringBuilder object explicitly.
Summary
- When String concatenation is completed using a statement, the performance is equivalent to that when StringBuilder is used.
- When you concatenate strings using multiple statements, consider merging these statements or explicitly using StringBuilder.
How does java increase the speed of String concatenation?
The use of StringBuffer, or StringBuilder... can be changed to a string.
Java String concatenation
It does not point to the same object.
Suppose there is another statement, String e = "test3"; Because String is final and cannot be modified, e can be considered as a constant.
When the String d = "test" + "3" is encountered, the compiler optimizes this statement to String d = "test3 ", because there is an identical Object e, d also points to e.
So d and e are the same object.
When processing String c = a + B, the compiler considers that the two variables are added and will not be optimized. Therefore, c and d are not the same object.
If a and B are defined
Final String a = "test ";
Final String B = "3 ";
In this case, String c = a + B becomes a constant addition, so the compiler will optimize it, that is, c and d are equal.
Ps: We recommend that you use a book "deep into java Virtual Machine" to introduce the underlying mechanism of java.