Out of the two methods in StringBuilder's append, which of the following code is better?
stringBuilder.append('\n');
or
stringBuilder.append("\n");
Equals is more efficient, it will only check if the strings match. Contains will search the for that text inside the string.
Using + Operator The + operator is one of the easiest ways to concatenate two strings in Java that is used by the vast majority of Java developers. We can also use it to concatenate the string with other data types such as an integer, long, etc.
If you are using two or three string concatenations, use a string. StringBuilder will improve performance in cases where you make repeated modifications to a string or concatenate many strings together. In short, use StringBuilder only for a large number of concatenations.
StringBuffer s are mutable, memory efficient, and thread-safe. Their downfall is the speed when compared to much faster StringBuilder s. As for StringBuilder s, they are also mutable and memory efficient, they are the fastest in string manipulation, but unfortunately they are not thread-safe.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With