JAVA principle difference in the String, StringBuilder, StringBuffer three

Difference in the three source:

  1. In java 8, which is jdk1.8, we can see part of the source code on a String
public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];
    }

We can see in the source code used to store an array of strings of characters are defined constants become final.

private final char value[];

So String is immutable string.

  1. In jdk1.8 in part on the source of StringBuilder
public final class StringBuilder
   extends AbstractStringBuilder
   implements java.io.Serializable, CharSequence
{

   /** use serialVersionUID for interoperability */
   static final long serialVersionUID = 4383685877147921099L;

   /**
    * Constructs a string builder with no characters in it and an
    * initial capacity of 16 characters.
    */
   public StringBuilder() {
       super(16);
   }
}
  1. jdk1.8 source portion in StringBuffer
public final class StringBuffer
   extends AbstractStringBuilder
   implements java.io.Serializable, CharSequence
{

   /**
    * A cache of the last value returned by toString. Cleared
    * whenever the StringBuffer is modified.
    */
   private transient char[] toStringCache;

   /** use serialVersionUID from JDK 1.0.2 for interoperability */
   static final long serialVersionUID = 3388685877147921107L;

   /**
    * Constructs a string buffer with no characters in it and an
    * initial capacity of 16 characters.
    */
   public StringBuffer() {
       super(16);
   }
}

4.StringBuilder and StringBuffer inherit AbstractStringBuilder, following are some of the source code AbstractStringBuilder

abstract class AbstractStringBuilder implements Appendable, CharSequence {
    /**
     * The value is used for character storage.
     */
    char[] value;

    /**
     * The count is the number of characters used.
     */
    int count;

AbstractStringBuilder found in the source code, used to store the string of characters is not defined as an array of final constant.
According to char[] value;this line of code, StringBuilder and StringBuffer strings are variable.


Three on whether the thread safety problems:
thread, we simply understood as the basic unit of each program execution.
String string is constant, it can not be changed, so String thread safe.

 private final char value[];

AbstractStringBuilder StringBuilder and StringBuffer is common parent class defines the basic operation of some of the string, such as expandCapacity (), append (), insert (), indexOf () method and other public.
StringBuffer method of adding a synchronization lock (synchronized) or method call added a synchronization lock (synchronized), so are thread-safe.

   @Override
    public synchronized String substring(int start, int end) {
        return super.substring(start, end);
    }

    /**
     * @throws StringIndexOutOfBoundsException {@inheritDoc}
     * @since      1.2
     */
    @Override
    public synchronized StringBuffer insert(int index, char[] str, int offset,
                                            int len)
    {
        toStringCache = null;
        super.insert(index, str, offset, len);
        return this;
    }

    public int indexOf(String str) {
       return indexOf(str, 0);        //存在 public synchronized int indexOf(String str, int fromIndex) 方法
 }

But did not add synchronization lock in a StringBuilder source code, so StringBuilder is not thread safe.


Three computing speed problem:
the StringBuilder> StringBuffer> String
the StringBuilder fastest, StringBuffer second, String slowest.
Because String is a string constant, see the following code:

String str="abc";
System.out.println(str);
str=str+"de";
System.out.println(str);

Our eyes look as if str was indeed changed, but not the case.
First, create a String object str, and the "abc" assigned to str, and then in the third row, in fact, has created a new object also named str, and then the value of the original str and "de" add up re-assigned to new str, str and the original will be garbage collection (GC) to reclaim lost, so, str not actually been changed, that is to say in front of the String object is immutable once created a.
So String string change is to re-create the object, re-assignment, re-create the object, reassigned ...... this cycle
but StringBuffer and StringBuilder can all be changed.

public static void testStringBuffer(){
        long start = System.currentTimeMillis();
        StringBuffer stringBuffer = new StringBuffer();
        for(int i = 0;i<200000;i++){
            stringBuffer.append(i);
        }
        System.out.println(System.currentTimeMillis() - start);
    }
public static void testStringBuilder(){
        long start = System.currentTimeMillis();
        StringBuilder stringBuilder = new StringBuilder();
        for(int i = 0;i<200000;i++){
            stringBuilder.append(i);
        }
        System.out.println(System.currentTimeMillis() - start);
    }
public static void main(String[] args) {
        // TODO Auto-generated method stub
        testStringBuffer();
        testStringBuilder();
    }

Results are as follows:
Here Insert Picture Description


Summary:
String: Apply a small amount of string manipulation case

StringBuilder: apply to the situation of a large number of operating under a single thread in the character buffer

A large number of cases suitable for multi-threaded operating under the character buffer: StringBuffer

Guess you like

Origin blog.csdn.net/fight252/article/details/90905397