StringBuilder的append方法有两种使用方式,以下哪种代码更好?
stringBuilder.append('\n');
或者
stringBuilder.append("\n");
使用单个char
(stringBuilder.append('\n')
)进行追加比追加一个String
(例如"\n"
)更节省工作量,即使String
只包含单个字符。
与基本执行单个赋值到value
数组的append(char c)
进行比较:
public AbstractStringBuilder append(char c) {
ensureCapacityInternal(count + 1);
value[count++] = c;
return this;
}
要调用append(String str)
,需要额外进行两个方法调用(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")
。
话虽如此,在特定情况下,你可能需要使用第三个选项-stringBuilder.append(System.lineSeperator())
。虽然这种方法的缺点是附加了一个String
(比附加一个char
慢),但它考虑到不同平台(例如Linux与Windows)使用不同的行分隔符,有时甚至由多个字符组成。 因此,可以认为stringBuilder.append(System.lineSeperator ())
是更正确的选项。
System.lineSeparator()
更正确的说法。这取决于具体的使用情况。 - xehpukJTextPane
时,你应该总是使用\n
。 - xehpuk
append
,那么某个代码块将会迭代该字符串并添加其中的每个字符。但是这不太可能产生可测量的性能差异。 - khelwoodchar
附加到StringBuilder
。在第二种情况下,您使用String
进行附加。这是非常琐碎的问题,我认为@GeorgeZougianos的评论是正确的。 - zlakadSystem.lineSeparator()
。如果在你的系统上\n
是错误的(例如在Windows上),那么代码将无法按预期工作,而这并不值得用更快的版本所节省下来的皮秒。 - Zabuzard