Tring is a string constant. StringBuffer is a string variable, thread-safe. StringBuilder is a string variable and the thread is not secure.
Speed: String<stringbuffer<stringbuilder
Why is string speed the slowest?
Because each time a string type is changed, it is equivalent to generating a new string object and then pointing the pointer at a new string object, so that the old object accumulates in memory when the new object is constantly generated, causing memory waste, The Java GC garbage collector reclaims old objects, slowing the program down severely. And StringBuilder is different, each operation is on the same object, and StringBuilder do not consider thread synchronization (StringBuffer is thread-safe, to consider thread synchronization), so StringBuilder fastest.
Many articles are recommended for use with StringBuilder, because StringBuilder is the fastest and most programs are single-threaded.
The StringBuilder and StringBuffer methods are basically the same, and the following examples give only string and StringBuffer tests.
[Java] View plain copy package com.xujin; public class test { public static void main (String [] args) { String a = "this " + "is a simple " + "example."; system.out.println (a); stringbuilder sb = new stringbuilder (); sb.insert (0, true); system.out.println (SB);//true sb.insert (0, "Hello,"); System.out.println (SB);//hello,true &NBSP;&NBSP;&NBSP;&NBSP;&NBsp; sb.setcharat (2, ' o '); System.out.println (SB);//heolo,true sb.reverse (); system.out.println (SB);//eurt,oloeh system.out.println (Sb.capacity ());//16 sb.trimtosize (); system.out.println (Sb.length ());//10 } }
Use Policy:
1, if the string does not add and subtract operation, use String.
2, if the string on the thread safety requirements, the use of StringBuffer.
3, if the string for thread safety does not require, and the pursuit of efficiency, the use of StringBuilder. Recommended use of StringBuilder.