The use of recursion can often lead to a cleaner implementation of your algorithms but when compared with implementations based on loops, recursive ones incur in the additional cost of allocating and managing a new stack frame for every method call performed, something that makes the recursive implementation slower and that can also quickly lead to stack exhaustion (aka stack overflow).

To avoid the risk of overflowing the stack, the recommended approach suggests to rewrite your algorithm employing tail recursion to leverage the tail call optimization that some compilers provide.

Read more

Leave a comment