我有以下包含这两种方法的示例class
:
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);
}
}
主类:
public static void main(String[] args) {
Process.countRecursive(0);
Process.countWhile(0);
}
输出:
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
但我想知道推荐使用哪种“技术”以及原因。
提前谢谢。
发布于 2012-12-19 23:56:12
由于方法调用开销和调用堆栈的使用,递归将变得更慢。
Java也没有执行尾部调用优化,所以不要指望它。(尽管JVM上有一些语言具有尾部调用优化功能,包括Clojure和Kotlin)
另一个缺点可能是在堆栈被填满的情况下存在StackOverflowError
的风险。
如果您这样做只是为了尝试一下,我建议使用VisualVM,它可以在java JDK中找到。它是一个分析器,可以用来对这种情况进行基准测试(或者,如果您使用的是操作系统,则可以要求一个开源的YourKit许可证)。
请注意,,我不推荐使用递归,只是为了花哨。如果你真的需要它,就使用它(例如,遍历树)。
发布于 2012-12-20 01:08:17
您应该使用时间度量来运行代码。下面是我对100个递归/ 100个while循环的输出:
Recursive time: 90941
While time: 5180
这清楚地表明,while循环比递归更快。
您可以通过运行以下代码来检查我的测量结果:
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));
}
}
发布于 2012-12-19 23:57:52
我不建议使用递归,因为每个递归都存储在堆栈中。因此,您需要为每个递归调用存储方法参数、局部变量等,以维护该调用之前的方法状态。
而且,你显然不应该在这种问题上使用递归。它应该留给一些特定的任务,只有当你真的无法避免使用它们的时候。
此外,您还可以对您的代码进行基准测试,看看哪一个运行得更快。你将会有一个想法。
https://stackoverflow.com/questions/13956158
复制相似问题