更新時間:2020-10-30 17:44:55 來源:動力節點 瀏覽1133次
字符串或串(String)是由數字、字母、下劃線組成的一串字符。對于字符串而言我們經常是要對其進行拼裝處理的通常以串的整體作為操作對象,如:在串中查找某個子串、求取一個子串、在串的某個位置上插入一個子串以及刪除一個子串等,字符串拼接方式也各有不同。
在java中提到了三種字符串拼接的方式:+、concat()以及append()方法。這三者之間存在什么區別呢?先看如下示例:
public class StringTest {
/**
* @desc 使用+、concat()、append()方法循環10W次
* @author chenssy
* @data 2013-11-16
* @param args
* @return void
*/
public static void main(String[] args) {
//+
long start_01 = System.currentTimeMillis();
String a = "a";
for(int i = 0 ; i < 100000 ; i++){
a += "b";
}
long end_01 = System.currentTimeMillis();
System.out.println(" + 所消耗的時間:" + (end_01 - start_01) + "毫米");
//concat()
long start_02 = System.currentTimeMillis();
String c = "c";
for(int i = 0 ; i < 100000 ; i++){
c = c.concat("d");
}
long end_02 = System.currentTimeMillis();
System.out.println("concat所消耗的時間:" + (end_02 - start_02) + "毫米");
//append
long start_03 = System.currentTimeMillis();
StringBuffer e = new StringBuffer("e");
for(int i = 0 ; i < 100000 ; i++){
e.append("d");
}
long end_03 = System.currentTimeMillis();
System.out.println("append所消耗的時間:" + (end_03 - start_03) + "毫米");
}
}
------------
Output:
+ 所消耗的時間:19080毫米
concat所消耗的時間:9089毫米
append所消耗的時間:10毫米
從上面的運行結果可以看出,append()速度最快,concat()次之,+最慢。原因請看下面分解:
1.+方式拼接字符串
在前面我們知道編譯器對+進行了優化,它是使用StringBuilder的append()方法來進行處理的,我們知道StringBuilder的速度比StringBuffer的速度更加快,但是為何運行速度還是那樣呢?主要是因為編譯器使用append()方法追加后要同toString()轉換成String字符串,也就說 str +=”b”等同于
str = new StringBuilder(str).append("b").toString();
它變慢的關鍵原因就在于new StringBuilder()和toString(),這里可是創建了10W個StringBuilder對象,而且每次還需要將其轉換成String,速度能不慢么?
2.concat()方法拼接字符串
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
char buf[] = new char[count + otherLen];
getChars(0, count, buf, 0);
str.getChars(0, otherLen, buf, count);
return new String(0, count + otherLen, buf);
}
這是concat()的源碼,它看上去就是一個數字拷貝形式,我們知道數組的處理速度是非常快的,但是由于該方法最后是這樣的:return new String(0, count + otherLen, buf);這同樣也創建了10W個字符串對象,這是它變慢的根本原因。
3.append()方法拼接字符串
public synchronized StringBuffer append(String str) {
super.append(str);
return this;
}
StringBuffer的append()方法是直接使用父類AbstractStringBuilder的append()方法,該方法的源碼如下:
public AbstractStringBuilder append(String str) {
if (str == null) str = "null";
int len = str.length();
if (len == 0) return this;
int newCount = count + len;
if (newCount > value.length)
expandCapacity(newCount);
str.getChars(0, len, value, count);
count = newCount;
return this;
}
與concat()方法相似,它也是進行字符數組處理的,加長,然后拷貝,但是請注意它最后是返回并沒有返回一個新串,而是返回本身,也就說這這個10W次的循環過程中,它并沒有產生新的字符串對象。
通過上面的分析,我們需要在合適的場所選擇合適的字符串拼接方式,但是并不一定就要選擇append()和concat()方法,原因在于+根據符合我們的編程習慣,只有到了使用append()和concat()方法確實是可以對我們系統的效率起到比較大的幫助,才會考慮。當然,你也可以觀看本站的Java基礎教程,掌握更多的字符串拼接方式。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習