The differences between string, StringBuffer, and StringBuilder in Java

Source: Internet
Author: User
Tags first string

1.String

2.Stringbuffer

3.StringBuilder

4. The difference between the three

5. Using policies

1.String

1  Public Final class String 2     implements java.io.Serializable, comparable<string>, charsequence {3/     * * */4     privatefinalchar  value[] ; 5 6 }

The first string is the final type and cannot be inherited.

The array used to hold the character is declared final, so it can only be assigned once and cannot be changed.

2.Stringbuffer

1  /*@since JDK1.02  */3   Public Final classStringBuffer4     extendsAbstractstringbuilder5     Implementsjava.io.Serializable, Charsequence6 {7 8     /**9 * A Cache of the last value returned by toString. ClearedTen * Whenever the StringBuffer is modified. One      */ A     Private transient Char[] tostringcache; -  - @Override the      Public synchronized intLength () { -         returncount; -     } -  + @Override -      Public synchronized intcapacity () { +         returnvalue.length; A     } at  -  - @Override -      Public synchronized voidEnsurecapacity (intminimumcapacity) { -         if(Minimumcapacity >value.length) { - expandcapacity (minimumcapacity); in         } -     } to  +}

Many methods for this class have the Synchronized keyword. Primarily for multithreaded environments

A string variable (Synchronized, thread-safe). If you want to modify the string content frequently, it is best to use stringbuffer for efficiency reasons, and if you want to turn to string type, you can call the ToString () method of StringBuffer.

The most common way to use this class is the Append and insert methods, which can be overloaded to accept arbitrary types of data. Append append character at the end, insert appends a string to a location

3.StringBuilder

1* @since 1.52*/3  Public Final classStringBuilder4     extendsAbstractstringbuilder5     Implementsjava.io.Serializable, Charsequence6 {7 8     /**Use Serialversionuid for interoperability*/9     Static Final LongSerialversionuid = 4383685877147921099L;Ten  One     /** A * Constructs a string builder with no characters in it and an - * Initial capacity of characters. -      */ the      PublicStringBuilder () { -         Super(16); -     } -  +     /** - * Constructs a string builder with no characters in it and an + * Initial capacity specified by the {@codecapacity} argument. A      * at      * @paramcapacity the initial capacity. -      * @throwsNegativearraysizeexception if the {@codecapacity} - * argument is less than {@code0}. -      */ -      PublicStringBuilder (intcapacity) { -         Super(capacity); in     } -  to}

StringBuilder: String variable (non-thread safe). Internally, the StringBuilder object is treated as a variable-length array that contains a sequence of characters.

Java.lang.StringBuilder is a variable sequence of characters that is JDK5.0 new. This class provides an API that is compatible with StringBuffer, but does not guarantee synchronization. This class is designed to be used as a simple replacement for stringbuffer, which is common when a string buffer is used by a single thread.

The method is constructed as follows:

Construction method Describe
StringBuilder () Create a StringBuilder object with a capacity of 16 (16 empty elements)
StringBuilder (Charsequence CS) Create a StringBuilder object containing CS with 16 empty elements appended to the end
StringBuilder (int initcapacity) Create a StringBuilder object with a capacity of initcapacity
StringBuilder (String s) Creates a StringBuilder object containing S, with 16 empty elements appended to the end

In most cases, StringBuilder > StringBuffer. This is mainly because the former does not need to consider thread safety.

4. The difference between the three

The main performance difference between string types and StringBuffer: string is an immutable object, so each time a string is changed, a new string object is generated and the pointer is pointed to the new string object. Therefore, it is best not to use string to change the content of the strings, because each generation of the object will have an impact on the system performance, especially when there is no reference object in memory, the JVM's GC will start to work, and will be degraded.

When using the StringBuffer class , the StringBuffer object itself is manipulated each time, instead of generating new objects and changing the object references. So in most cases it is recommended to use StringBuffer, especially if the string object is often changed .

But the situation is out of the list:

1 String a= "a" + "B" + "C"; 2 stringbuffer sb=new  stringbuffer (); 3 sb.append ("a"). Append ("B"). Append ("C");

The first one is better than the second, because Java compilation sets the value of variable a directly to ABC.

But the second way to do this is to change the variables.

5. Using policies

(1) Basic principles: If you want to manipulate a small amount of data, using string, single-threaded operation of large amounts of data, with StringBuilder, multi-threaded operation of a large number of data, with StringBuffer.

(2) Do not use the String class "+" for frequent splicing , because that performance is very poor, should use the StringBuffer or StringBuilder class, which is a more important principle in Java optimization.

(3) In order to achieve better performance, you should specify their capacity whenever possible when constructing stirngbuffer or Stirngbuilder. Of course, if you manipulate a string length (length) of no more than 16 characters, it is not necessary to construct an object with a capacity of 16 by default when no capacity is specified (capacity). Not specifying capacity can significantly degrade performance.

(4) StringBuilder is generally used inside the method to complete a similar "+" function, because the thread is unsafe, so after use can be discarded. StringBuffer are mainly used in global variables.

(5) In the same case, using stirngbuilder compared to using StringBuffer can only obtain the performance improvement of around 10%~15%, but the risk of multi-threading insecurity. In real-world modular programming, a programmer in charge of a module does not necessarily have a clear sense of whether the module will run in a multithreaded environment, so unless the system bottleneck is determined to be on the StringBuffer, and it is determined that your module will not run in multithreaded mode, can use StringBuilder, or use StringBuffer.

(6) is the key point to use StringBuilder or StringBuffer is whether your business module is multithreaded.

Reference: http://blog.csdn.net/kingzone_2008/article/details/9220691>http://blog.csdn.net/kingzone_2008/article/ details/9220691

The differences between string, StringBuffer, and StringBuilder in Java

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.