Java-11.2 "+" and StringBuilder
In this chapter, we will discuss the + and StringBuilder in the string.
1. Example
package com.ray.ch11;public class Test {public static void main(String[] args) {String a = a + b + c;String d = a + d;}}
Here we use the java analysis program command javap to see how the class is actually executed?
Note the following two sentences in the red box:
(1) the compiler is optimized for "a" + B + c and directly becomes abc
(2) The second sentence comes from a + d. It first comes out of a StringBuilder and then adds it. This is also the result of Compiler optimization.
However, there are limits to the optimization of this compiler, and in some cases it is cumbersome.
2. Performance Comparison Test
The following example compares the performance between "+" and StringBuilder.
Use "+ ":
package com.ray.ch11;public class Test {public static void main(String[] args) {String a = ;long startTime = System.currentTimeMillis();for (int i = 0; i < 100000; i++) {a += a;}long endTime = System.currentTimeMillis();System.out.println(endTime - startTime);}}
Output:
20031
Use StringBuilder:
package com.ray.ch11;public class Test {public static void main(String[] args) {StringBuilder sb = new StringBuilder();long startTime = System.currentTimeMillis();for (int i = 0; i < 100000; i++) {sb.append(a);}long endTime = System.currentTimeMillis();System.out.println(endTime - startTime);}}
Output:
16
Compare the two outputs to produce a very wide comparison result, that is, the performance of "+" is much lower than that of StringBuilder.
Why?
Let's look at the following two figures:
Is the javap diagram of the first group of code:
As described above, the cycle is 100000 times, and the place in the red box is new 100000 times. Each new time consumes a lot of time. Therefore, the time is very long.
Is the javap diagram of the second group of code:
The code in the red box is just a new StringBuilder. The following is the append string on the object, which greatly reduces the execution time.
Conclusion:
(1) In most cases, the compiler will optimize our strings.
(2) In some extreme cases, compiler optimization may cause performance problems.
(3) Use "+". In the compiler's opinion, it is just using Stringbuilder.
Summary: This chapter briefly introduces + and StringBuilder, and compares the performance of the two.