[String constants of java] differences between String, StringBuffer and StringBuilder

Source: Internet
Author: User

String constant
StringBuffer string variable thread security)

StringBuilder string variable is not thread-safe)

Next, let's look at the append method implementation of the two:

First look at the StringBuffer:

public synchronized StringBuffer append(Object obj) {        super.append(String.valueOf(obj));        return this;    }                public synchronized StringBuffer append(String str) {        super.append(str);        return this;    }

Let's look at StringBuilder's:

public StringBuilder append(Object obj) {     return append(String.valueOf(obj)); }         public StringBuilder append(String str) {     super.append(str);     return this; }


Comparing the source code above, we found that the append Implementation of StirngBuffer and StringBuilder both calls the parent class implementation. The only difference is that StringBuffer is thread-safe. synchronized is added to the method, while StringBuilder is 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, which is common when the string buffer is used by a single thread ). 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.



The test code is as follows:

Public class testssb {/** Creates a new instance of testssb */final static int ttime = 10000; // number of test cycles public testssb () {} public void test (String s) {long begin = System. currentTimeMillis (); for (int I = 0; I <ttime; I ++) {s + = "add" ;}long over = System. currentTimeMillis (); System. out. println ("operation" + s. getClass (). the getName () + "type is used for:" + (over-begin) + "millisecond");} public void test (StringBuffer s) {long begin = System. currentTimeMillis (); for (int I = 0; I <ttime; I ++) {s. append ("add");} long over = System. currentTimeMillis (); System. out. println ("operation" + s. getClass (). the getName () + "type is used for:" + (over-begin) + "millisecond");} public void test (StringBuilder s) {long begin = System. currentTimeMillis (); for (int I = 0; I <ttime; I ++) {s. append ("add");} long over = System. currentTimeMillis (); System. out. println ("operation" + s. getClass (). getName () + "type used for:" + (over-begin) + "millisecond");} // String concatenation test public void test2 () {String s2 = "abadf"; long begin = System. currentTimeMillis (); for (int I = 0; I <ttime; I ++) {String s = s2 + s2 + s2;} long over = System. currentTimeMillis (); System. out. println ("Operation String object reference addition type used for:" + (over-begin) + "millisecond");} public void test3 () {long begin = System. currentTimeMillis (); for (int I = 0; I <ttime; I ++) {String s = "abadf" + "abadf" + "abadf ";} long over = System. currentTimeMillis (); System. out. println ("Operation String addition time:" + (over-begin) + "millisecond");} public static void main (String [] args) {String s1 = "abc"; StringBuffer sb1 = new StringBuffer ("abc"); StringBuilder sb2 = new StringBuilder ("abc"); testssb t = new testssb (); t. test (s1); t. test (sb1); t. test (sb2); t. test2 (); t. test3 ();}}

The test results for the ttime of the number of cycles being 10000 are as follows:

Operate java. lang. the time used by the String type is 4392 milliseconds for java operations. lang. the time used by the StringBuffer type is: 0 milliseconds for java operations. lang. the StringBuilder type is used for the following time: 0 millisecond operation String object reference addition time: 15 millisecond operation string addition time: 0 millisecond

It seems that there is no difference between StringBuffer and StringBuilder. Add the ttime to 30000 times:

Operate java. lang. the time used by the String type is 53444 milliseconds for java operations. lang. the StringBuffer type is used for 15 milliseconds to operate java. lang. the time used by StringBuilder is: 15 ms. the time used for String object reference addition type is: 31 Ms. the time used for string addition is: 0 ms.

The performance of StringBuffer and StringBuilder is not significantly different. increase it to 100000. Here we will not add the String type test, because the testing of the large data volume of the String type will be slow ......

The time used to operate the java. lang. StringBuffer type is 31 Ms. The time used to operate java. lang. StringBuilder type is 16 Ms.



The time used to operate the java. lang. StringBuffer type is 265 milliseconds.

The time used to operate java. lang. StringBuilder is 219 milliseconds.


This article from the "CEO Road" blog, please be sure to keep this source http://zhaohaibo.blog.51cto.com/7808533/1287553

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.