問題分析:
首先,看看兩段代碼的運行結果,兩段代碼分別是:
第一段代碼,關於String.concat()方法的測試:
1 public static void main(String[] args) 2 { 3 //String stringA = "hello"; 4 String stringA = new String("hello"); 5 testConcat test = new testConcat(); 6 7 test.change(stringA); 8 9 System.out.println(stringA); 10 } 11 public void change(String stringA) 12 { 13 stringA = stringA.concat("world"); 14 }
第二段代碼,StringBuffer.append()方法的測試:
1 public static void main(String[] args) 2 { 3 StringBuffer stringBufferA = new StringBuffer("hello"); 4 testAppend test = new testAppend(); 5 6 test.change(stringBufferA); 7 8 System.out.println(stringBufferA); 9 } 10 public void change(StringBuffer stringBufferA) 11 { 12 stringBufferA.append("World"); 13 }
在實際的運行這兩段代碼后,得到的結果是:
第一段代碼結果:hello
第二段代碼結果:helloWorld
由此,可以看出StringBuffer.append()所改變的是源引用的值,不會依賴於方法返回值,而String.concat()在進行字符串拼接的時候,會產生很多的臨時對象來保存,最后在拼接結束后,需要把這個結果臨時對象進行返回給接收值進行再指向,需要依賴於方法的返回值,執行的效率也會隨着字符數的增加而降低,不是真正的引用源
總結:
在所使用的字符串需要經常變更的情況下,使用StringBuffer效率更高,可以使用StringBuffer進行字符串的變更操作,操作完成后再還給String,操作方法:String -> StringBuffer -> 更改字符串 -> String
待續...
