If you enable all inspections under the heading "Performance issues", you'll get a warning (as in the title) about the following code:
StringBuilder sb = new StringBuilder("Two");
String s = "One" + sb.toString();
I realise the toString()
is unnecessary, but in what way is it a performance issue?
There is no point in using a StringBuilder
if you're going to use the string concatenation operator (+
), which creates a StringBuilder
behind the scenes, leading to the creation of two StringBuilder
objects instead of one. You can simply re-use the StringBuilder
to concatenate strings:
StringBuilder sb = new StringBuilder("One");
sb.append("Two");
String s = sb.toString();
The original code is equivalent to:
StringBuilder sb = new StringBuilder("Two");
StringBuilder sb2 = new StringBuilder("One");
String s = sb2.append(sb.toString()).toString();
Another aspect related to the warning (which honestly has less to do with performance than code optimization) is that the toString()
is redundant when used with the +
operand. This is because the compiler will automatically call the toString()
. This is what you already guessed in your question, and is explained in the Java Language Specification:
(from https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.18.1):
If only one operand expression is of type
String
, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.
where section 5.1.11 says:
If the reference is
null
, it is converted to the string"null"
(four ASCII charactersn
,u
,l
,l
).Otherwise, the conversion is performed as if by an invocation of the
toString
method of the referenced object with no arguments; but if the result of invoking thetoString
method isnull
, then the string"null"
is used instead.