sb is essentially a StringBuffer object. Directly sb+"" is calling sb.toString() to splice it with "". In addition, StringBuffer is thread-safe. Why use StringBuilder or StringBuffer? The reason is that the String class in Jdk is of final type, but why can the final modified version exist in the form of String str = s + "";? Because in jvm, every time + is executed, a temporary String object will be created, and then the String str = a + b; you see; is actually String str = new String(a) + new String(b); In this way, if there are too many strings to be spliced, many String objects will be created. Therefore, the overhead of gc will increase. Therefore, such frequent operations do not directly use string splicing, but use StringBuilder or StringBuffer. replace.
sb is essentially a StringBuffer object. Directly sb+"" is calling sb.toString() to splice it with "". In addition, StringBuffer is thread-safe. Why use StringBuilder or StringBuffer? The reason is that the String class in Jdk is of final type, but why can the final modified version exist in the form of String str = s + "";? Because in jvm, every time + is executed, a temporary String object will be created, and then the String str = a + b; you see; is actually String str = new String(a) + new String(b); In this way, if there are too many strings to be spliced, many String objects will be created. Therefore, the overhead of gc will increase. Therefore, such frequent operations do not directly use string splicing, but use StringBuilder or StringBuffer. replace.