Which one is better to pass to StringBuilder.append?

v0ld3m0rt :

Out of the two methods in StringBuilder's append, which of the following code is better?

stringBuilder.append('\n'); 

or

stringBuilder.append("\n");
Eran :

Appending a single char (stringBuilder.append('\n')) requires less work than appending a String (such as "\n"), even if the String contains only a single character.

Compare append(char c), which basically performs a single assignment to the value array:

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

To append(String str), which requires additional 2 method calls (str.getChars() and 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;
}

which calls

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);
}

Therefore, in terms of performance, stringBuilder.append('\n') is better than stringBuilder.append("\n").

That said, in the specific case of \n, you might want to use a third option - stringBuilder.append(System.lineSeperator ()) . While this has the downside of appending a String (which is slower than appending a char), it accounts for the fact that different platforms (for example Linux vs. Windows) use different line separators, which sometimes even consist of more than one character. Hence stringBuilder.append(System.lineSeperator ()) can be considered more correct.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=471473&siteId=1