This article references http://wenku.baidu.com/view/8de1a06b011ca300a6c390d2.html
1. String Class Object
A. Once created, it cannot be changed.
B. If you assign a new value to a referenced object, but direct the new reference to a new object, the old object remains unchanged. (That is, each time a new value is assigned, a new object is created)
2. stringbuffer, stringbuilder:
A. The object content can be modified. Each operation will operate on the object itself, rather than generating a new object.
3. The following is a test of the class.
package com.jue.test;public class MainTest {public static void main(String[] args) {test1();// 1685test2();// 12}private static void test1() {long startTime = System.currentTimeMillis();String s = "abc";for (int i = 0; i < 10000; i++) {s += "123";}long currentTime = System.currentTimeMillis();System.out.println(currentTime - startTime);}private static void test2() {long startTime = System.currentTimeMillis();StringBuffer s = new StringBuffer("abc");for (int i = 0; i < 10000; i++) {s.append("123");}long currentTime = System.currentTimeMillis();System.out.println(currentTime - startTime);}}
Result
Test 1: 1685
Test2: 12
4. In some cases, directly adding is faster than stringbuffer
private static void test3() {long startTime = System.currentTimeMillis();StringBuilder s = new StringBuilder("abc");for (int i = 0; i < 10000000; i++) {s.append("123");}long currentTime = System.currentTimeMillis();System.out.println(currentTime - startTime);}private static void test4() {long startTime = System.currentTimeMillis();for (int i = 0; i < 10000; i++) {String s1 = "123" + "456" + "789" + "abc" + "def";}long currentTime = System.currentTimeMillis();System.out.println(currentTime - startTime);}
Result:
Test3: 0 ~ 1
Test4: 80 ~ 90
5. stringbuffer and stringbuilder
Stringbuffer is thread-safe.
Stringbuilder is non-thread-safe. It is better to use stringbuilder if there is no thread escape.