Skip to content
Advertisement

Are recursive methods always better than iterative methods in Java? [closed]

Are recursive methods always better than iterative methods in Java?

Also can they always be used in place of iteration and vice-versa?

Advertisement

Answer

Are recursive methods always better than iterative methods in java?

No

Also can they always be used in place of iteration and vice-versa?

You can always make an iterative function from a recursive one (if memory can handle it, see interesting link here).

For some cases, it’s better to use recursion (like when dealing with trees.. traveling on a binary tree, etc.). For me, if using loops isn’t more complicated and much more difficult than a recursion, I prefer to use loops.

Recursion uses more memory but is sometimes clearer and more readable. Using loops increases the performance, but recursion can sometimes be better for the programmer (and their performance).

So, for the conclusion, deciding what to use – recursion or iteration, depends on what you want to implement, and what’s more important for you (readability, performance…), and asking recursion or iteration is like asking for elegance or performance.


Example

Consider these two implementation for the factorial:

Iterative:

private int Factorial(int num)
{
    int result = 1;
    if (num <= 1) 
       return result;
    while (num > 1)
    {
        result * = num;
        num--;
    }
    return result;
}

Recursion:

private int Factorial(int num)
{
    if (num <= 1) 
        return 1;
    return num * Factorial(num - 1);
}

Which method is more readable?

Obviously the recursive one, it is straight forward and can be written and successfully run from the first try – It is simply translating math definition into Java!

Which method is more efficient?

Take for example num = 40, here is a time comparison:

long start = System.nanoTime();
int res = Factorial(40);
long end = System.nanoTime();
long elapsed = end - start;
        
System.out.println("Time: " + elapsed); 

2993 for the recursive

2138 for the iterative

of course, the difference will be larger when num is larger.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement