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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With