Java string and stringbuffer usage differences 2007-05-22 10: 03string class is used to indicate those strings that will not be changed after creation, it is immutable. The stringbuffer class is used to represent variable strings and provides methods to modify underlying strings.
-- When concatenating characters, use the stringbuffer class instead of the string class, because the former is faster than the latter.
Indeed, inProgramIn many cases, we will concatenate strings, which is simple.CodeExample:
String STR = "you are nice .";
STR + = "I love you so much .";
If the stringbuffer class is used, the Code is as follows:
Stringbuffer STR = new stringbuffer ("You are nice .");
Str. append ("I love you so much .");
From http://wzdoxu.iteye.com/blog/262022
On the surface, the string class uses only one plus sign (+) to concatenate strings, while the stringbuffer class calls an append () method. Is it more concise and simple to implement? Otherwise, let's take a look at what happened inside the program:
After compilation, the bytecode (bytecode) of the program shows the essence: When the string class object is directly spliced, JVM creates a temporary stringbuffer Class Object and calls its append () this is because the string class is unchangeable and the concatenation operation has to use the stringbuffer class (and -- JVM will set "you are nice. "and" I love you so much. "created as two new string objects ). Then, the temporary stringbuffer object is transformed into a string, which is expensive! We can see that in this simple splicing process, we have the program create four objects: two strings to be spliced, a temporary stringbuffer, and the string that finally transforms stringbuffer into -- it is not the original STR, and the referenced name is not changed, but it points to the New String object.
If you directly use the stringbuffer class, the program will generate only two objects: the initial stringbuffer and the string ("I love you so much. "), you do not need to create a temporary stringbuffer class object and then convert it back to the string object.
We can imagine how much additional system overhead will be incurred when we use the string class for direct operations when our strings are to be concatenated by several segments cyclically, and how many useless temporary stringbuffer objects will be generated, and how many unnecessary forced type conversions are processed.