StringBuilder 字符串拼接擴容


String str = a + b + c(a,b,c都是變量,非常量)

實際執行時,"+"操作是通過創建一個StringBuilder來操作的,即:

StringBuilder temp = new StringBuilder();
temp.append("a");
temp.append("b");
temp.append("c");
temp.toString();

 StringBuilder初始容量是16個char,可以通過 temp.capacity()方法得到。

當字符長度超過16個字符會進行擴容。

 public AbstractStringBuilder append(String str) {
	if (str == null) str = "null";
        int len = str.length();
	if (len == 0) return this;
	int newCount = count + len;//count-當前StringBuilder字符串的長度
	if (newCount > value.length)
	    expandCapacity(newCount);
	str.getChars(0, len, value, count);
	count = newCount;
	return this;
    }

 

void expandCapacity(int minimumCapacity) {
	int newCapacity = (value.length + 1) * 2;
        if (newCapacity < 0) {
            newCapacity = Integer.MAX_VALUE;
        } else if (minimumCapacity > newCapacity) {
	    newCapacity = minimumCapacity;
	}
        value = Arrays.copyOf(value, newCapacity);
    }

每次擴容都會擴容到當前字符串的2倍長度。

多個字符串拼接

1. 小字符串多,大字符串只有一兩個時

  優先拼接小字符串,最后在拼接大字符串。

  因為如果先拼接大字符串,則第一次擴容后的長度為count+len(大字符串長度)即minimumCapacity,且沒有空閑空間。再次拼接小字符串即使是一個字符串,也會擴容,擴容后的StringBuilder中會有很多空閑空間。

2. 大字符串多,小字符串少 

  優先拼接大字符串。每次擴容長度為(value.length + 1) * 2,擴容以后浪費空間比較少。

但都不是絕對的,視實際業務情況而定。

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM