String, StringBuilder and StringBuffer difference of (turn)

I believe we have seen a lot of difference comparing String and StringBuffer articles, but also understand the difference between the two, however, since Java 5.0 release, our comparative list will be more of a target, and this is the StringBuilder class. String class is immutable class, any change to the initiator generates a new String String object; StringBuffer is the variable type, changes its meaning any string generation will not produce a new object, a variable and immutable object of this class has been complete, then why why introduce new StringBuilder class? I believe we have this doubt, I also do so. Here, we look at the reasons for the introduction of the class.

      Why is there so much comparing String and StringBuffer article?

      The reason is that when changing the contents of the string, using StringBuffer better performance can be obtained. Since it is for better performance, then the use of StringBuffer to get the best performance yet?

      The answer is NO!

      why?

      If you've read "Think in Java", but on the inside HashTable and HashMap describe the difference between that part of the chapter are more familiar with it, you must also understand why. Yes, that support for thread synchronization to ensure the thread safety problems leading to performance degradation. HashTable are thread-safe, many methods are synchronized method, and HashMap is not thread safe, but its performance in single-threaded programs is higher than HashTable. The difference between StringBuffer and StringBuilder class is also here, the newly introduced StringBuilder class is not thread-safe, but its performance in single-threaded is higher than StringBuffer. If you do not believe this, try the following example:

package com.hct.test;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author: chengtai.he
 * @created:2009-12-9 上午09:59:57
 */
public class StringBuilderTester {
 private static final String base = " base string. ";
 private static final int count = 2000000;

 public static void stringTest() {
  long begin, end;
  begin = System.currentTimeMillis();
  String test = new String(base);
  for (int i = 0; i < count/100; i++) {
   test = test + " add ";
  }
  end = System.currentTimeMillis();
  System.out.println((end - begin)
    + " millis has elapsed when used String. ");
 }

 public static void stringBufferTest() {
  long begin, end;
  begin = System.currentTimeMillis();
  StringBuffer test = new StringBuffer(base);
  for (int i = 0; i < count; i++) {
   test = test.append(" add ");
  }
  end = System.currentTimeMillis();
  System.out.println((end - begin)
    + " millis has elapsed when used StringBuffer. ");
 }

 public static void stringBuilderTest() {
  long begin, end;
  begin = System.currentTimeMillis();
  StringBuilder test = new StringBuilder(base);
  for (int i = 0; i < count; i++) {
   test = test.append(" add ");
  }
  end = System.currentTimeMillis();
  System.out.println((end - begin)
    + " millis has elapsed when used StringBuilder. ");
 }

 public static String appendItemsToStringBuiler(List list) {
  StringBuilder b = new StringBuilder();

  for (Iterator i = list.iterator(); i.hasNext();) {
   b.append(i.next()).append(" ");
  }

  return b.toString();
 }

 public static void addToStringBuilder() {
  List list = new ArrayList();
  list.add(" I ");
  list.add(" play ");
  list.add(" Bourgeois ");
  list.add(" guitars ");
  list.add(" and ");
  list.add(" Huber ");
  list.add(" banjos ");

  System.out.println(StringBuilderTester.appendItemsToStirngBuffer(list));
 }

 public static String appendItemsToStirngBuffer(List list) {
  StringBuffer b = new StringBuffer();

  for (Iterator i = list.iterator(); i.hasNext();) {
   b.append(i.next()).append(" ");
  }

  return b.toString();
 }

 public static void addToStringBuffer() {
  List list = new ArrayList();
  list.add(" I ");
  list.add(" play ");
  list.add(" Bourgeois ");
  list.add(" guitars ");
  list.add(" and ");
  list.add(" Huber ");
  list.add(" banjos ");

  System.out.println(StringBuilderTester.appendItemsToStirngBuffer(list));
 }

 public static void main(String[] args) {
  stringTest();
  stringBufferTest();
  stringBuilderTest();
  addToStringBuffer();
  addToStringBuilder();
 }
}

The above procedure was as follows:
5266 Used String of millis has the when the Elapsed. 
375 of millis has the when the Elapsed Used StringBuffer. 
281 of millis has the Elapsed Used the when the StringBuilder. 
 The I Play Bourgeois Guitars and Huber Banjos  
 the I Play Bourgeois Guitars and Huber Banjos 
from the above results point of view this difference in performance in three classes single-threaded program at a glance, when the use of String objects, even if the number of runs is the use of only 1/100 of other objects, its execution time is still more than 25 times higher than other objects; and the use StringBuffer object and using the difference StringBuilder object is also obvious, the former is about 1.5 times the latter. Thus, if our program is running in single-threaded, or without regard to thread synchronization problem, we should give priority to the use of the StringBuilder class; of course, if you want to ensure thread-safe, natural non-none other than StringBuffer.

In addition to support for multithreading is not the same, but these two classes using almost no difference, the above example is a good description. appendItemsToStringBuiler appendItemsToStirngBuffer and two methods were used in addition to external objects and the StringBuffer StringBuilder, other exactly, but the effect is the same.

to sum up:

Variability
String class using the character array stored in a string, Private
Final char value [], so string objects are immutable. StringBuilder and StringBuffer are inherited from AbstractStringBuilder class, but also the use of an array of characters in the string stored in AbstractStringBuilder, char []
value, these two objects are variable.
Thread safety
in String objects are immutable, it can be understood as a constant thread safe. AbstractStringBuilder StringBuilder and StringBuffer is common parent class defines the basic operation of some of the string, such as expandCapacity, append, insert, indexOf other public methods. StringBuffer method adds genlock or method call added a synchronization lock, so are thread-safe. StringBuilder and no method plus genlock, so not thread-safe.
Performance
each time of a change of type String, generates a new String object, then the pointer to the new String object. StringBuffer every time to
StringBuffer object itself to operate, instead of generating new object and change the object reference. Use the same circumstances
StirngBuilder compared to using
StringBuffer only get about 10% to 15% performance increase, but bear the risk of multithreading unsafe.

Transfer from http://www.cnblogs.com/Fskjb/archive/2010/04/19/1715176.html

Published 15 original articles · won praise 7 · views 10000 +

Guess you like

Origin blog.csdn.net/J_M_S_H_T/article/details/88181805