Java foundation StringBuffer, StringBuilder Principle Analysis

  StringBuilder and StringBuffer role is to handle strings, but the String class itself also has a lot of ways to handle strings, so why the introduction of these two classes it?

  First, look at the following example

  public static void main(String[] args) {

  String str0 = "hel,lo,wor,l,d";

  long start = System.currentTimeMillis();

  for (int i = 0; i < 100000; i++){

  str0 + = i;

  }

  System.out.println(System.currentTimeMillis() - start);

  StringBuilder sb = new StringBuilder("hel,lo,wor,l,d");

  long start1 = System.currentTimeMillis();

  for (int i = 0; i < 100000; i++){

  sb.append(i);

  }

  System.out.println(System.currentTimeMillis() - start1);

  StringBuffer sbf = new StringBuffer("hel,lo,wor,l,d");

  long start2 = System.currentTimeMillis();

  for (int i = 0; i < 100000; i++){

  sbf.append(i);

  }

  System.out.println(System.currentTimeMillis() - start2);

  }

  3 at the above code cycle is completed the same function, string concatenation, performed following results:

  36823

  3

  4

  As can be seen too much difference in execution time, in order to solve a lot of string concatenation String This scenario is not good at business, the introduction of StringBuffer and StringBuilder.

  First, we analyze why a lot of string concatenation String In this scenario so slow?

  Because the String itself immutable, we return a new String object to any action of the will, then the current String variable to point to a new object, and the original String object will be recovered GC, it will create a lot faster in the new cycle objects, a large number of the original object will continue to be GC recovery, the time consumed is very frightening, and very large memory footprint.

  Next, we compared the difference between String, StringBuffer and StringBuilder of

  String  StringBuffer  StringBuilder

  final modification, can not be inherited final modification, can not be inherited final modification, can not be inherited

  String constant, the string variable created immutable, string variables may be dynamically modified, can be dynamically modified

  There is no security thread thread safety, all public methods to modify unsafe by the synchronized thread

  Up to a lot of strings together a large number of inefficient string concatenation efficiency is very high efficiency of a large number of string concatenation

  StringBuffer and StringBuilder achieve very similar to the following StringBuilder briefly explain append () method basic principle

  1. First create a StringBuilder

  StringBuilder sb1 = new StringBuilder();

  StringBuilder sb2 = new StringBuilder(100);

  StringBuilder string by operation of the char [] is achieved by creating a default constructor StringBuilder, which creates internal char [] The default length of 16, of course, can call the constructor overloaded transmission original length (such Recommended , because it reduces the number of array capacity expansion, improve efficiency).

  /**

  * Constructs a string builder with no characters in it and an

  * initial capacity of 16 characters.

  */

  public StringBuilder() {

  super(16);

  }

  2. StringBuilder the append () method

  Every call append (str) method first determines whether the array length will be sufficient to add the passed string

  /**

  * Appends the specified string to this character sequence.

  *

  * The characters of the {@code String} argument are appended, in

  * order, increasing the length of this sequence by the length of the

  * argument. If {@code str} is {@code null}, then the four

  * characters {@code "null"} are appended.

  *

  * @param str a string.

  * @return a reference to this object.

  */

  public AbstractStringBuilder append(String str) {

  if (str == null)

  return appendNull();

  int len = str.length();

  ensureCapacityInternal(count + len);

  str.getChars(0, len, value, count);

  count + = only;

  return this;

  }

  /**

  * For positive values of {@code minimumCapacity}, this method

  * behaves like {@code ensureCapacity}, however it is never

  * synchronized.

  * If {@code minimumCapacity} is non positive due to numeric

  * overflow, this method throws {@code OutOfMemoryError}.

  */

  private void ensureCapacityInternal(int minimumCapacity) {

  // overflow-conscious code

  if (minimumCapacity - value.length > 0) {

  value = Arrays.copyOf(value,

  newCapacity(minimumCapacity));

  }

  } Wuxi Bohai hospital abortion http://www.89906662.com/

  If the string length of the array has been stored characters transmitted +> length of the array, then the data on the need for the expansion

  /**

  * Returns a capacity at least as large as the given minimum capacity.

  * Returns the current capacity increased by the same amount + 2 if

  * that suffices.

  * Will not return a capacity greater than {@code MAX_ARRAY_SIZE}

  * unless the given minimum capacity is greater than that.

  *

  * @param minCapacity the desired minimum capacity

  * @throws OutOfMemoryError if minCapacity is less than zero or

  * greater than Integer.MAX_VALUE

  */

  private int newCapacity(int minCapacity) {

  // overflow-conscious code

  int newCapacity = (value.length << 1) + 2;

  if (newCapacity - minCapacity < 0) {

  newCapacity = minCapacity;

  }

  return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)

  ? hugeCapacity(minCapacity)

  : newCapacity;

  }

  Expansion rules are as follows: the length of the array is set to the default "(current array length * 2) + 2", but the array after expansion if this rule is not sufficient to add a new string, it is necessary to set the length of the array "array within transmitting the character string length + length. "

  So if we know the approximate length of a string of splicing more than 100 characters, we can set the initial length of 150 or 200, and avoid or reduce the number of array expansion, thereby improving efficiency.

Guess you like

Origin www.cnblogs.com/djw12333/p/11356781.html