I've written some code which has a lot of string creation. To try to avoid the expensive string creation over and over, I'm using the java StringBuilder
class.
My code is a bit like this:
public String createString(){
StringBuilder stringBuilder = new StringBuilder();
for(int i = 0; i < Integer.MAX_VALUE ; i++){ //its not actually this, but it's a large loop.
stringBuilder.append(appendString())
}
return stringBuilder.toString();
}
The appendString
method also instantiates a StringBuilder
and appends to it.
To save time, I noticed that I could make my appendString
method return a StringBuilder
, rather than a String
which avoids returning the stringBuilder using the .toString()
method like so:
public StringBuilder appendString(){
StringBuilder appendBuilder = new StringBuilder();
appendBuilder.append("whatever");
return appendBuilder;
}
This is all fine until I looked at the StringBuilder
documentation and realised that there is no append(StringBuilder stringBuilder)
method on the StringBuilder
class, only an append(String string)
.
So my question is, how does this code run? Is it casting StringBuilder
to String
anyway?