总是避免 Java 中的递归方法?

发布于 2024-12-05 19:30:56 字数 438 浏览 0 评论 0原文

我记得应该始终避免在 Java 中使用递归方法调用。我认为原因是,将调用的方法保存在上所产生的开销不值得在实现中减少代码行数。

然而,最近有人告诉我,如果递归实现很好地捕获了问题空间,则事实并非如此。我没有完全理解这一点,因为每个递归方法都可以迭代实现,例如通过使用堆栈。

有几个问题可以通过使用递归实现来解决,例如遍历树数据结构。

在 Java 中是否应该始终避免递归实现还是?如果不是,那么决定是否使用递归或迭代实现的良好标准是什么。产生的开销重要还是已经优化了?我在 stackoverflow 上读到,Java 不支持尾递归优化

I recall that one should always avoid using recursive method calls in Java. I thought the reasons are, that the overhead procuded by saving the invoked methods on the heap is not worth the reduced lines of code in the implementation.

However, I was told lately that this is not true, if the recursive implementation captures the problem space quite well. I did not understand this fully, since every recursive method can be implemented iteratively, for instance by using a stack.

There are several problems which can be solved by using recursive implementations, for instance traversing through the tree data structure.

Should one always avoid recursive implementations in Java or not? If not, what is a good criteria to decide, whether to use recursive or iterative implemenation. Is the produced overhead important or is it optimized anyway? I've read on stackoverflow, that tail recursive optimization is not supported in Java.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

于我来说 2024-12-12 19:30:56

不,您不应该避免 Java 本身的递归。它在 JVM 中有它的局限性,主要是你不能像函数式语言那样深度递归(因为,正如你所指出的,JVM 不支持尾递归优化),但它在这些语言中肯定是有用和可用的。限制。

因此,只要它能让您的解决方案变得更简单,就可以使用它。是的,您始终可以将递归展开为迭代,但生成的代码通常可能更难以理解和维护。递归的性能通常不是一个需要提前担心的问题。首先通过测量证明递归是程序中的性能瓶颈,然后您可以重写它。

No, you should not avoid recursion in Java per se. It has its limitations in the JVM, mainly that you can't recurse as deep as e.g. in functional languages can (because, as you noted, tail recursion optimization is not supported by the JVM), but it is certainly useful and usable within those limits.

So use it whenever it makes your solution simpler. Yes, you can always unroll recursion into iteration, but the resulting code may often be more difficult to understand and maintain. Performance of recursion is usually not an issue to be worry about in advance. First prove with measurements that recursion is a performance bottleneck in your program, then you can rewrite it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文