StringBuffer and StringBuilder
String is immutable, StringBuffer/StringBuilder is mutable.
每次對String進行修改都會產生新的物件,若經常改變同一個字串,最好不要用String。
public class StringImmutableTest { public static void main(String[] args) { String str = new String("hello"); str.concat(" world"); //會產生新的字串(hello world),但沒被引用 System.out.println("String: " + str); StringBuffer sb = new StringBuffer("hello"); sb.append(" world"); System.out.println("StringBuffer: " + sb); } }
String: hello StringBuffer: hello world
StringBuffer is synchronized(thread safe). StringBuilder is non-synchronized, so it faster than StringBuffer.
確定不會在多執緒下執行,用StringBuilder以獲得較好的效能
使用
+
來串接字串時,編輯器會做最佳化:String s = "a" + "b" + " c";
→String s = "abc"
String s = s1 + s2;
→String s = (new StringBuffer()).append(s1).append(s2).toString();
但如果在迴圈內串接字串,還是要改用StringBuilder,才能確保不會一直產生新的物件。
String out = ""; for( int i = 0; i < 10000 ; i++ ) { out = out + i; // => out = new StringBuilder().append(out).append(i).toString(); } return out;
StringBuilder out = new StringBuilder(); for( int i = 0 ; i < 10000; i++ ) { out.append(i); } return out.toString();
其他常用方法
public class StringBuilderTest { public static void main(String[] args) { System.out.println(new StringBuilder("hello").append("world")); System.out.println(new StringBuilder("hello").length()); System.out.println(new StringBuilder("hello").reverse()); System.out.println(new StringBuilder("hello").insert(5, "world")); System.out.println(new StringBuilder("hello").delete(1, 3)); System.out.println(new StringBuilder("hello").substring(0, 2)); } }
helloworld 5 olleh helloworld hlo he
Reference
[ Java 文章收集 ] 是 String , StringBuffer 還是 StringBuilder
Java: String concat vs StringBuilder - optimised, so what should I do?