问题描述
递归方法总是优于Java中的迭代方法吗?
Are recursive methods always better than iterative methods in Java?
它们也可以总是用来代替迭代,反之亦然吗?
Also can they always be used in place of iteration and vice-versa?
推荐答案
否
您可以始终使递归函数成为迭代函数。 (如果内存可以处理它,请参阅有趣的链接)
You can always make a recursive function an iterative 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 his performance).
因此,总而言之,决定使用什么 - 递归或迭代,取决于你想要实现什么,以及对你来说更重要(可读性,性能......)和询问递归或迭代就像要求优雅或表现。
So, for 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.
考虑 factorial 的这两个实现:
迭代:
private int Factorial(int num)
{
int result = 1;
if (num <= 1)
return result;
while (num > 1)
{
result * = num;
num--;
}
return result;
}
递归:
private int Factorial(int num)
{
if (num <= 1)
return 1;
return num * Factorial(num - 1);
}
哪种方法更具可读性?
显然是递归的,它是直接的,可以编写并从第一次尝试成功运行 - 它只是将数学定义转换为 Java
!
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
!
哪种方法效率更高?
示例 num = 40
,这是时间比较:
long start = System.nanoTime();
int res = Factorial(40);
long end = System.nanoTime();
long elapsed = end - start;
System.out.println("Time: " + elapsed);
2993 递归
2993 for the recursive
2138 迭代
2138 for the iterative
当然差异将会当num更大时,它会变大..
of course the difference will be larger when num is larger..
这篇关于递归方法总是比Java中的迭代方法更好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!