开发者

Always avoid recursive methods in Java? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 11 years ago.

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 impleme开发者_如何学Gonted 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜