3 ms·
> Does anybody know why this was? In general, recursive calls require stack frames, which is main memory. Tail recursion is however relatively easily transform
by formerly_proven 6y ago
> Does anybody know why this was?
In general, recursive calls require stack frames, which is main memory. Tail recursion is however relatively easily transformed into the equivalent while loop, which then does not consume stack frames.
Consider:
def factorial(n):
if n is 1: return 1
else: return n * factorial(n - 1)
For factorial(12345), this requires 12345 stack frames, but with tail-call optimization the compiler can transform the function into something this:
def factorial(n):
accum = n
while n > 1:
n -= 1
accum *= n
return accum
Besides this, some older languages just didn't have a real stack. All variables would be allocated as-if they are global variables and there would be a small array of return addresses and the current index into it somewhere. Naturally, you could not nest function calls deeper than this array was long.
For Fortran the reason may be that Fortran was (and still is) used a lot for numeric code and loops lend themselves more naturally to optimization and vectorization compared to arbitrary recursion.