String StringBuffer Stringbuider in Java in-depth understanding

Source: Internet
Author: User

The first thing to understand is that Java only uses wrapper types that are immutable, and what are immutable types? As the name implies, this type of object, once created, cannot change any of the properties of the object, regardless of which method is called. String source, all of its properties are private final, so, only when constructing the string object, these properties can be modified, the method of the string class need to return a string, such as Substring,concat, and other methods, Will first construct a new string object and return it, and the original string object will not change.

The difference between stringbuffer and arrays:

StringBuffer: variable length, and the length of the array is immutable.

StringBuffer and Stringbuider:

StringBuffer is synchronized, thread-safe, used in multi-threading.

The Stringbuider is non-thread-safe and is used in a single thread (more common). This class is a simple replacement for the StringBuffer class.


String class and Stringbuider Main performance Differences :

String: each time a string object is changed, a new string object is generated, and then the pointer points to the new string object, so it is better not to use strings to change the contents of the text frequently. Because each generated object will have an impact on the system performance, especially when the non-referenced objects in memory are many, the JVM's GC will start to work, and the systems will degrade.


stringbuffer: When using a StringBuffer object, the object itself is manipulated each time, rather than generating a new object and changing the object reference, so many times, especially if the string object changes frequently Use StringBuffer.

But using: String s1= "This" + "was" + "a" + "simple" + "test";

Sb=new StringBuffer ("This is a") than StringBuffer. Append ("simple"). Append ("test");

Fast, because in Javacompiler, the first statement is automatically compiled to: String s1= "This is a simple test";

However, the concatenation of the string from another string object, Javacompiler will not automatically convert, the speed is slow, such as the following.

String s2= "This is a";

String s3= "Simple";

String s4= "Test";

String S1=s2+s3+s4;

at this time, Java compiler will behave in the same manner as the original way to do. The concatenation (or +) operation of String takes advantage of the Append method Implementation of the StringBuffer (or Stringbuider), at which point, if S2,S3,S4 is defined by string, You need to create an extra one when stitching

After StringBuffer (or Stringbuider), the StringBuffer is converted to string, and S1 can know the specific value at run time. If using StringBuffer

, you do not need to create additional stringbuffer.

Principle of Use:

1. If you operate a small amount of data, use a string, single-threaded to manipulate large amounts of data with Stringbuider. Multithreading large amounts of data with StringBuffer.

2. Do not use the String class "+" operation, to frequent splicing, because that performance is very poor, you should use StringBuffer or stringbuider. This is also an important principle in Java optimization.

3. For better performance, it is possible to specify their capacity when constructing stringbuffer or Stringbuider. If the string length (length) of the operation does not exceed the 16-character object, it is not necessary. If not specified, no capacity will degrade performance.

4.Stringbuider is generally used inside the method to accomplish a function similar to "+". Because threads are unsafe, they can be discarded when they are exhausted. StringBuffer is mainly used in global variables.

5. In the same situation, the use of Stringbuider compared to the use of StringBuffer only to obtain the performance improvement of around 10%~ 5%, but the risk of multithreading insecurity.


The really unique disadvantage of non-mutable classes (immutable) is that a separate object is required for each different value.

Pros: Easy to design, implement and use, error-prone, thread-safe, and its value will never change in its lifetime.

StringBuffer acts as a companying class for string (companion tired)


Common methods of StringBuffer:

StringBuffer Append ("data");//Add the specified data (various data) as parameters to the end of the existing data




StringBuffer Insert (Index, "data");//You can insert data into the position of the specified index

StringBuffer Delete (start,end);//delete Start (contains) to end (not included)

Wait a minute.. can go to the manual query. No longer listed here.



Finally, let me give you an example:

Package Com.test;public class Test {public    static void Main (string[] args) {      string[] arr=new string[10];        for (int i=0;i<arr.length;i++) {           arr[i]= "value" +i;                }        String result= "";        for (String S:arr) {//This foreach statement produces 10 objects, nine useless garbage objects, which are eventually recycled by GC, reduces system performance, and finally leaves only one we want to have <span style= "White-space:pre" The object used by the ></span>//.            result+=s;        }        SYSTEM.OUT.PRINTLN (result);     
Output Result:
Value0value1value2value3value4value5value6value7value8value9;



One more example:

String S=new string ("abc");

In the above statement, "ABC" at compile time is itself an object in the pool, while executing the new String ("ABC") at run time, the object in the pool is copied into the heap, and the reference to this object in the heap is given to S. So the above sentence creates two string objects, one in the heap in the string pool.


Example: How many objects are created by the following program?

Package Com.test;public class Test {public    static void Main (string[] args) {      String a,b,c;      A= "a";//The first object      b= "B";//The second      a=a+b;//third, at which point the reference variable a points to the "AB" object, the original point "a" object becomes a garbage object, will be recycled by GC      StringBuffer d=new StringBuffer ("abc");//Direct production of two objects. One in the string pool one in heap      d=d.append ("567");//The Operation modified on the D object itself, does not produce a new object.     }}   
conclusion, a total of 5 objects were produced.




String StringBuffer Stringbuider in Java in-depth understanding

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.