Always avoid recursive methods in Java?

I remember that you should always avoid using recursive method calls in Java . I thought the reason was that the overhead incurred while saving the invoked methods on the heap was not worth the shortened lines of code in the implementation.

However, recently I was told that this is not true if the recursive implementation fixes the problem space pretty well. I did not understand this completely, since each recursive method can be implemented iteratively , for example, using the stack.

There are several problems that can be solved using recursive implementations, for example, through the tree data structure.

Is it always to avoid recursive implementations in Java or not ? If not, what is a good criterion for deciding whether to use a recursive or iterative implementation. In any case, is the overhead generated important or optimized? I read about stackoverflow that recursive optimization is not supported in Java.

+6
source share
1 answer

No, you should not avoid recursion in Java as such. It has its limitations in the JVM, mainly that you cannot repeat it as deeply as, for example, in functional languages โ€‹โ€‹(since, as you noted, tail recursion optimization is not supported by the JVM), but it is certainly useful and can be used in these limits.

So use it when it simplifies your decision. Yes, you can always deploy recursion to iteration, but the resulting code can often be more difficult to understand and maintain. Recursion efficiency is usually not a problem to worry about beforehand. First, prove by measuring that recursion is the performance bottleneck in your program, then you can rewrite it.

+9
source

Source: https://habr.com/ru/post/897820/


All Articles