字符串進行拼接有三種方法:加號、contact方法和StringBuffer(StringBuilder),StringBuffer和StringBuilder拼接方法類似,只是StringBuilder用於單線程,而StringBuffer是線程安全的,用於多線程。java
主要探討一下以上三種拼接方法的效率,固然大概效率都是知道的,以下數組
StringBuffer>concat>」>」安全
雖然知道這個結果,可是也更得知道因此然。多線程
1.「+」方法拼接字符串app
雖然編譯器對字符串的加號作了優化,它會使用StringBuilder的append方法進行追加,那麼按道理來講,它的執行時間也應該和StringBuilder差很少啊,可是否則,實際實現以下:ide
Str=new StringBuilder(str).append(「c」).toString();
它每次拼接都會建立一個StringBuilder對象,而且還要調用toString()方法將其轉換爲字符串,這樣性能就大大下降了。性能
2.concat方法拼接字符串優化
首先看下源碼:ui
public String concat(String str){ int otherLen = str.length(); //若是追加的字符串長度爲0,則返回字符串自己 if(otherLen == 0){ return this; } //字符數組,容納的是新字符串的字符 char buf[] = new char[count + otherLen]; //取出原始字符串放到buf數組中 getChars(0, count, buf, 0); //追加的字符串轉換成字符數組,添加到buf中 str.getChars(0, otherLen, buf, count); //複製字符數組,產生一個新的字符串 return new String(0, count + otherLen, buf); }
總體上看上去就是一個數組拷貝,雖然在內存中的處理都是原子性操做,速度很是快,可是最後一句return,每次的concat操做都會建立一個String對象,這樣就會讓concat的速度慢下來。this
3.StringBuilder.append()方法拼接
源碼以下:
public AbstractStringBuilder append(String str){ //若是爲null值,則把null做爲字符串處理 if(str==null) str = "null"; int len = str.length(); //字符長度爲0,則返回自己 if(len == 0) return this; int newCount = count +len; //追加後的字符數組長度是否超過當前值 if(newCount > value.length()){ //加長,並作數組拷貝 expanCapacity(newCount); } //字符串複製到目標數組 str.getChars(0, len, value, count); count = newCount; return this; }
整個append方法都在作字符數組處理,加長,而後數組拷貝,這些都是基本的數據處理,沒有建立任何對象,因此速度是很是快的。