簡體   English   中英

哪一個更好地傳遞給StringBuilder.append?

[英]Which one is better to pass to StringBuilder.append?

在StringBuilder附加的兩個方法中,以下哪個代碼更好?

stringBuilder.append('\n'); 

要么

stringBuilder.append("\n");

附加一個單個charstringBuilder.append('\\n')需要比附加一個較少的工作String (諸如"\\n" ),即使String僅包含單個字符。

比較append(char c) ,它基本上對value數組執行單個賦值:

public AbstractStringBuilder append(char c) {
    ensureCapacityInternal(count + 1);
    value[count++] = c;
    return this;
}

append(String str) ,這需要額外的2個方法調用( str.getChars()System.arraycopy ):

public AbstractStringBuilder append(String str) {
    if (str == null)
        return appendNull();
    int len = str.length();
    ensureCapacityInternal(count + len);
    str.getChars(0, len, value, count);
    count += len;
    return this;
}

哪個叫

public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
    if (srcBegin < 0) {
        throw new StringIndexOutOfBoundsException(srcBegin);
    }
    if (srcEnd > value.length) {
        throw new StringIndexOutOfBoundsException(srcEnd);
    }
    if (srcBegin > srcEnd) {
        throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
    }
    System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
}

因此,在性能方面, stringBuilder.append('\\n')優於stringBuilder.append("\\n")

也就是說,在\\n的特定情況下,您可能想要使用第三個選項 - stringBuilder.append(System.lineSeperator ()) 雖然這有附加String的缺點(比附加char更慢),但它解釋了不同平台(例如Linux與Windows)使用不同的行分隔符這一事實,有時候甚至包含多個字符。 因此可以認為stringBuilder.append(System.lineSeperator ())更正確。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM