Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Always avoid recursive methods in Java? [closed]

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.

like image 347
Konrad Reiche Avatar asked Sep 22 '11 11:09

Konrad Reiche


1 Answers

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.

like image 195
Péter Török Avatar answered Sep 19 '22 13:09

Péter Török