Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion runtime implementation Java vs. other/functionals languages?

I like recursion, but at Java you meet an dead end at some point. E.g. I had a case where recursion with ~100K iterations wouldn't work (StackOverflowError). Badly I had to switch to annoying "imperative looping" for this runtime stack-limit reasons.

I wonder how other (especially functional) languages bypass stack-overflowing during runtime? I guess especially functional language runtimes handle this problem better because recursion is core-concept...

Has somebody some information or external resources?

like image 381
manuel aldana Avatar asked Sep 28 '10 10:09

manuel aldana


1 Answers

Most languages have compiler optimizations for tail recursion. Tail recursion means that the recursive call should be the last call of your recursive method. The compiler can then optimize this into a loop, preventing stack overflow errors from happening.

I'm not sure whether all javac implementations implement tail recursion. It is not something that is required by the specification. However, it's an important optimization technique for any recursive program, so I suppose the mainstream implementations do provide tail recursion.

You can test this yourself by taking a (simple) non-tail-recursive program that generates a StackOverflowError and make it tail-recursive (calculating a factorial, for example).

EDIT: There has been a question about tail recursion in Java before, as indicated in a comment by user sje397. Also take a look at Stephen C's answer to this question, which provides some additional info.

like image 68
Ronald Wildenberg Avatar answered Oct 19 '22 10:10

Ronald Wildenberg