Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should one use StringBuilder in a recursive function?

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.

like image 425
Zaya Avatar asked Apr 18 '26 13:04

Zaya


1 Answers

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());
like image 57
user7294900 Avatar answered Apr 21 '26 02:04

user7294900