Which is faster in Java, while or using recursive method?
You should run code with time measurement. Here you have my output for 100 recursions/ 100 while loops:
Recursive time: 90941
While time: 5180
This clearly shows that while loop is faster than recursion.
You can check my measurements by running this code:
public class Process {
public Process() {
}
public static void countRecursive(int num) {
num++;
if (num <= 100) countRecursive(num);
else return;
}
public static void countWhile(int num) {
do
num++;
while (num <= 100);
}
public static void main(String[] args) {
Long start = System.nanoTime();
Process.countRecursive(0);
System.out.println("Recursive time: " + (System.nanoTime() - start));
Long startWhile = System.nanoTime();
Process.countWhile(0);
System.out.println("While time: " + (System.nanoTime() - startWhile));
}
}
I would not suggest using Recursion, as each recursion is stored on stack. So, you need to store method parameters, local variables, etc, for each recursive call, to maintain the state of method before that call.
Also, you should obviously not go with recursion with this kind of problem. It should be left for some specific task, only when you really can't avoid using them.
Further, you can also benchmark your code to see which one runs faster. You will get an idea.
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).