I understand that the purpose of StringBuilder
(usually) is to avoid creating objects over and over in Java when iterating over strings, especially in a loop.
I'm wondering if it's worth it to use it in a recursive function that returns a string. In other words, which of the following is more efficient?
public String recursive(int n) {
String retStr = "s";
if (n==0) {
return retStr;
}
else {
return retStr + recursive(n-1);
}
}
or
public String recursive(int n) {
String retStr = "s";
StringBuilder sb = new StringBuilder();
if (n==0) {
return retStr;
}
else {
return sb.append(retStr).append(recursive(n-1)).toString();
}
}
If I had to guess, the first one seems less complex, because either way you have to create a new object, be it a String
or a StringBuilder
, every time, but I could be wrong.
You can add StringBuilder to recursive method:
public String recursive(int n, StringBuilder sb) {
String retStr = "s";
if (n==0) {
return retStr;
}
else {
return sb.append(retStr).append(recursive(n-1, sb)).toString();
}
}
and call it
recursive(100, new StringBuilder());