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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With