字符串操作是編寫程序中最常見的行爲,本文對String、StringBuilder、StringBuffer三個類在字符串處理方面的效率進行分析。
Java中最常見也是應用最廣泛的類就是String類。
- String:Strings are constant; their values cannot be changed after they are created.
這是JDK對String的解釋,意思是:String是常量,一旦創建後它的值不能被修改。
先看String對象是如何創建的:
- String str1 = “abc”;
- String str2 = new String(“abc”);
這是我們常見的兩種形式。
第一種方式創建的字符串會放在棧裏,更確切的是常量池中,常量池就是用來保存在編譯階段確定好了大小的數據,一般我們定義的int等基本數據類型就保存在這裏。其具體的一個流程就是,編譯器首先檢查常量池,看看有沒有一個“abc”,如果沒有則創建。如果有的話,則則直接把str1指向那個位置。
第二種創建字符串的方法是通過new關鍵字,還是java的內存分配,java會將new的對象放在堆中,這一部分對象是在運行時創建的對象。所以我們每一次new的時候,都會創建不同的對象,即便是堆中已經有了一個一模一樣的。
下面的程序將驗證上面的說法。
- String str1 = "abc";
- String str2 = new String("abc");
- String str3 = "abc";
- String str4 = new String("abc");
- System.out.println(str1==str2);//false
- System.out.println(str1 == str3);//true
- System.out.println(str2 == str4);//false
- // When the intern method is invoked, if the pool already contains a
- // string equal to this String object as determined by the
- // equals(Object) method, then the string from the pool is returned.
- // Otherwise, this String object is added to the pool and a reference to
- // this String object is returned.
- str2 = str2.intern();
- System.out.println(str1==str2);//true
- //output:
- //false
- //true
- //false
- //true
以上程序中用兩種方式創建的4個對象,”==”比較的是地址,從結果可以看到str1和str3相同,指向同一個對象。而str2和str4比較返回結果是false,說明str2和str4指向的不是同一個對象。
(上面用到了一個比較少見的方法:intern。在str2調用了intern方法後對str1和str2進行比較返回true,可以從代碼註釋中看明白,intern方法返回常量池中內容和該對象相同的對象,如果常量池中不存在,則將該對象加入到常量池中。)
String對象是不變的,那爲什麼可以進行str+=”abc”這樣的操作?其實類似這樣的操作是新生成了一個String對象,包含str和abc連接後的字符串。
- package test;
- public class StringTest {
- public static void main(String[] args) {
- String str1 = "abc";
- str1 += "123";
- }
- }
從編譯之後的class可以看出編譯器自動引入了StringBuilder類,通過它的初始化方法創建了StringBuilder對象,通過append方法添加了內容,調用toString返回連接後的對象。以上內容證明了String對象是不可變的,連接操作實際是返回了新的對象。如果是循環多次進行連接,將不斷的創建StringBuilder對象,append新內容,toString成String對象。這就帶來了String類處理字符串更改操作的效率問題。
- public class StringTest {
- public static void main(String[] args) {
- long start, end;
- StringBuilder strBuilder = new StringBuilder(" ");
- start = System.currentTimeMillis();
- for (int i = 0; i < 100000; i++) {
- strBuilder.append(" ");
- }
- end = System.currentTimeMillis();
- System.out.println("StringBuilder append: " + (end - start) + "ms");
- String str = " ";
- start = System.currentTimeMillis();
- for (int i = 0; i < 100000; i++) {
- str += " ";
- }
- end = System.currentTimeMillis();
- System.out.println("String +: " + (end - start) + "ms");
- }
- }
可以看到String和StringBuilder在效率方便的差距。
- StringBuffer:A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified.
- StringBuilder:A mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization.
StringBuffer是可變的、線程安全的字符串。StringBuilder就是StringBuffer的非線程同步的版本,二者的方法差不多,只是一個線程安全(適用於多線程)一個沒有線程安全(適用於單線程)。