String splicing, when to use StringBuilder

Recently, I suddenly thought of the problem of String string splicing, so I did a demo test. In the end, when String type strings are spliced, in which case will they go and use StringBulider for string splicing, and in which case will they be compiled? Does the processor optimize the code? Not much to say, let’s watch the demo first

 

# Question

 

Case 1

 

 

It can be found that the result of str == str2 is false, then we are looking at the next example.

 

 

Case 2

 

At this time, the result of the comparison of the two strings is true.

 

# Explore the problem

 

At this time, the question arises, why are the results inconsistent? Use the command javap -c TestDemo.class in the cmd window to decompile the bytecode file. Found the problem?

 

 

It can be seen that in case 1, the bottom layer of the java code goes to StringBuilder, performs string splicing, and then calls the toString method of StringBuilder.

 

 

In case 2, the class file was decompiled, and it was found that there was a little change in the code, and StringBuilder was not used for string splicing.

 

# to sum up

 

1. In case 1, through the splicing of variables and strings, java needs to find the value corresponding to the variable in the memory before completing the string splicing. In this way, the java compiler cannot be optimized, and it can only be spliced ​​by StringBuilder String, and then call the toString method. Of course, the returned result is different from the memory address of the string 111 in the constant pool, so the result is false.

 

2. In case 2, write the value directly in the expression. Java does not need to find the corresponding value in the memory according to the variable. It can directly optimize the expression when compiling. The optimized expression starts from "111" + " "Directly becomes "111", the two String variables both point to the 111 string of the constant pool, so the result is true;

Guess you like

Origin blog.csdn.net/jcmj123456/article/details/108438837