Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is faster in Java, while or using recursive method?

I have the following sample class with these two methods:

Process.java:

public class Process {

    public Process() {
    }

    public static void countRecursive(int num) {
        System.out.println("countRecursive: " + num++);
        if (num <= 10) countRecursive(num);
        else return;
    }

    public static void countWhile(int num) {
        do System.out.println("countWhile: " + num++);
        while (num <= 10);
    }

}

Main class:

public static void main(String[] args) {        

    Process.countRecursive(0);
    Process.countWhile(0);

}

Output:

countRecursive: 0
countRecursive: 1
countRecursive: 2
countRecursive: 3
countRecursive: 4
countRecursive: 5
countRecursive: 6
countRecursive: 7
countRecursive: 8
countRecursive: 9
countRecursive: 10

countWhile: 0
countWhile: 1
countWhile: 2
countWhile: 3
countWhile: 4
countWhile: 5
countWhile: 6
countWhile: 7
countWhile: 8
countWhile: 9
countWhile: 10

But I want to know which "technique" is recommended to use and why.

Thanks in advance.

like image 488
Oscar Jara Avatar asked Dec 19 '12 15:12

Oscar Jara


1 Answers

Recursion will be slower because of the method call overhead and call stack usage.

Java isn't performing tail call optimization either so don't count on it. (Although there are languages on the JVM which do have tail call optimization including Clojure and Kotlin)

Another drawback might be the risk of a StackOverflowError in case you are filling up the stack.

If you are doing this just to try things out I suggest using VisualVM which can be found in the java JDK. It is a profiler which can be used to benchmark this kind of situation (or you can ask for an open source YourKit license if you're working on OSS).

Please note that I do not recommend using recursion just to be fancy. Use it if you really need it (traversing trees for example).

like image 68
Adam Arold Avatar answered Oct 11 '22 10:10

Adam Arold