Differences between string, stringbuffer, and stringbuilder in Java

Source: Internet
Author: User

The difference between string and stringbuffer can be said to be numerous online materials. However, when I saw this article, I felt that the small examples in the article were representative. So I made a summary.

There are three classes in Java to take charge of character operations.

1. character operates on a single character,

2. String operations on a string of characters. Immutable class.

3. stringbuffer also operates on a string of characters, but it can be a variable class.

String:
Yes. The object is not of the original type.
An unchangeable object. Once created, its value cannot be modified.
To modify an existing String object, create a new object and save the new value.
String is a final class, which cannot be inherited.

Stringbuffer:
It is a mutable object. objects are not re-created as strings when modified.
It can only be created by constructors,
Stringbuffer sb = new stringbuffer ();
Note: you cannot pay for a value by using a value symbol.
SB = "Welcome to here! "; // Error
After the object is created, the memory space is allocated in the memory, and a NULL is initially saved to stringbuffer.
You can use its append method to pay a value.
SB. append ("hello ");

Stringbuffer is more efficient than string in string connection operations:

String STR = new string ("Welcome ");
STR + = "here ";
In fact, by creating a stringbuffer, let Hou call append (), and finally
Then convert stringbuffer tosting ();
In this case, the string connection operation is more than the stringbuffer operation, of course, the efficiency is reduced.

Since the string object is an immutable object, each operation of sting creates a new object to save the new value.
In this way, the original object will be useless and it will be recycled. This will also affect the performance.

Take a look at the following code:
Repeat 26 English letters for 5000 times,

String tempstr = "abcdefghijklmnopqrstuvwxyz ";
Int times = 5000;
Long lstart1 = system. currenttimemillis ();
String STR = "";
For (INT I = 0; I <times; I ++ ){
STR + = tempstr;
}
Long lend1 = system. currenttimemillis ();
Long time = (lend1-lstart1 );
System. Out. println (time );
Unfortunately, my computer is not a supercomputer, and the result is usually about 46687.
That is, 46 seconds.
Let's take a look at the following code:

String tempstr = "abcdefghijklmnopqrstuvwxyz ";
Int times = 5000;
Long lstart2 = system. currenttimemillis ();
Stringbuffer sb = new stringbuffer ();
For (INT I = 0; I <times; I ++ ){
SB. append (tempstr );
}
Long lend2 = system. currenttimemillis ();
Long time2 = (lend2-lstart2 );
System. Out. println (time2 );
The result is 16. Sometimes it is 0.
Therefore, the conclusion is obvious that the stringbuffer speed is almost ten thousand times faster than that of string. Of course, this data is not very accurate. Because the number of cycles is 100000, the difference is greater. Try it.

According to the above:

STR + = "here ";
In fact, by creating a stringbuffer, let Hou call append (), and finally
Then convert stringbuffer tosting ();

So STR + = "here"; can be equivalent

Stringbuffer sb = new stringbuffer (STR );

SB. append ("here ");

STR = sb. tostring ();

Therefore, the code that uses "+" to connect to a string is basically equivalent to the following code:

String tempstr = "abcdefghijklmnopqrstuvwxyz ";
Int times = 5000;
Long lstart2 = system. currenttimemillis ();
String STR = "";
For (INT I = 0; I <times; I ++ ){
Stringbuffer sb = new stringbuffer (STR );
SB. append (tempstr );
STR = sb. tostring ();
}
Long lend2 = system. currenttimemillis ();
Long time2 = (lend2-lstart2 );
System. Out. println (time2 );
The average execution time is about 46922, that is, 46 seconds.

Else ---------------------------------------------------------------------------------------------------------------------------------

Stringbuffer maintains a fixed-size string buffer. When the string length exceeds the size of stringbuffer, it will automatically increase. The insert and append methods are mainly used. It is recommended to assemble strings during runtime,

Stringbuilder: After jdk5, there will be a stringbuider equivalent to stringbuffer. The difference is that stringbuffer is thread-safe, and stringbuilder is single-threaded and does not provide synchronization, which is theoretically more efficient.

String is a built-in system type and is final. Defining a string will generate an instance and a reference to the instance address.

If a string is defined during compilation, for example:

String A = "name ";
A + = "is ";
A + = "good ";

Although this method is not recommended, the compiler will optimize the code during compilation, so it can still be understood as: string a = "name is good "; if stringbuffer is used at this time, it will be postponed to the runtime for processing. In contrast, it will be more efficient and flexible than stringbuffer.
String constant
Stringbuffer string variable (thread safety)
Stringbuilder string variable (non-thread-safe)
In short, the main performance difference between the string type and the stringbuffer type is that the string type is an immutable object, therefore, every time the string type is changed, it is equivalent to generating a new String object, and then pointing the pointer to the New String object, therefore, it is best not to use a string that often changes the content, because every time an object is generated, it will affect the system performance, especially when there are more referenced objects in the memory, the GC of JVM will start to work, and the speed will be quite slow.
If the stringbuffer class is used, the results will be different. Each result will operate on the stringbuffer object itself, instead of generating a new object, and then change the object reference. Therefore, we generally recommend using stringbuffer, especially when string objects change frequently. In some special cases, the String concatenation of the string object is actually interpreted by JVM as the concatenation of the stringbuffer object. Therefore, the speed of the string object in these cases is not slower than that of the stringbuffer object, in particular, in the generation of the following string objects, the string efficiency is much faster than that of stringbuffer:
String S1 = "this is only a" + "simple" + "test ";
Stringbuffer sb = new stringbuilder ("This is only a"). append ("simple"). append ("test ");
You will be surprised to find that the speed of generating the string S1 object is too fast, and the stringbuffer speed is not dominant at all. In fact, this is a JVM trick.
String S1 = "this is only a" + "simple" + "test"; actually:
String S1 = "this is only a simple test"; so of course it doesn't take much time. However, you should note that if your string is from another string object, the speed will not be so fast. For example:
String S2 = "this is only ";
String S3 = "simple ";
String S4 = "test ";
String S1 = S2 + S3 + S4;
At this time, the JVM will follow the original method in a regular manner.

In most cases, stringbuffer> string
Stringbuffer
Java. Lang. stringbuffer thread-safe variable character sequence. A string buffer similar to a string, but cannot be modified. Although it contains a specific character sequence at any time point, the length and content of the sequence can be changed by calling some methods.
The string buffer can be safely used for multiple threads. These methods can be synchronized as necessary, so all the operations on any specific instance are in serial order, this sequence is consistent with the method call sequence of each involved thread.
The main operations on stringbuffer are append and insert methods. You can reload these methods to accept any type of data. Each method can effectively convert the given data to a string, and then append or insert the character of the string into the string buffer. The append method always adds these characters to the end of the buffer, while the insert method adds the characters at the specified point.
For example, if z references a string buffer object whose current content is "start", this method calls Z. append ("Le") causes the string buffer to contain "startle", while Z. insert (4, "Le") will change the string buffer to include "starlet ".
In most cases, stringbuilder> stringbuffer
Java. Lang. stringbuilde
A variable character sequence of Java. Lang. stringbuilder is added to 5.0. This class provides a stringbuffer-compatible API, but does not guarantee synchronization. This class is designed as a simple replacement of stringbuffer, used when the string buffer is used by a single thread (this is common ). If possible, we recommend that you use this class first, because in most implementations, It is faster than stringbuffer. The two methods are basically the same.
Through unofficial tests, the tests of stringbuilder and stringbuffer are summarized as follows:

1. To achieve better performance, specify the capacity of stirngbuffer or stirngbuilder as much as possible. Of course, if the length of the string you operate is no longer than 16 characters.

2. In the same case, use stirngbuilder to obtain only 10% ~ The performance is improved by about 15%, but the risk of multi-thread security is required. In practical Modular programming, the programmer in charge of a module may not be able to clearly determine whether the module will be run in a multi-threaded environment. Therefore: unless you are sure that the bottleneck of your system is on stringbuffer and that your module will not run in multi-thread mode, use stringbuffer.

3. It is more important to use the existing analogy to introduce new classes. Many programmers do not specify the capacity when using stringbuffer (at least I have seen it). If such a habit is introduced into the use of stringbuilder, you will only be able to achieve performance improvement of about 10% (don't forget, you have to risk multithreading); but if you use the stringbuffer of the specified capacity, you will get a performance improvement of about 45% immediately, or even about 30% faster than the stirngbuilder that does not use the specified capacity.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.