Tail Regeneration Optimization in JavaScript

JavaScript only optimizes a recursive step in a non-recursive loop if it is the last expression in a block (IIUC). Does this mean that the right recursive call will be optimized, and the left recursive call will NOT be in the next?

function fibonacci(n) {
  if(n < 2) return n;
  return fibonacci(n-1) + fibonacci(n-2);
}
+4
source share
1 answer

Does this mean that the right recursive call will be optimized, and the left recursive call will NOT be in the next?

I do not think so. TCO is only possible by directly returning another function. Since your function processes both results before returning them, none of the calls can be tail-optimized.

Low level explanation

In terms of a stack-based machine, this code:

function fun1()
   return fun2(42)

function fun2(arg)
    return arg + 1

fun1:
    push 42
    call fun2
    result = pop
    push result
    exit

fun2:
    arg = pop
    arg = arg + 1
    push arg
    exit

TCO call-pop-push fun2:

fun1:
    push 42
    goto fun2
    exit

, , :

fun1:
    push n - 1
    call fun2
    result1 = pop

    push n - 2
    call fun2
    result2 = pop

    result3 = result1 + result2
    push result3
    exit

, fun1 .

: , , JS- TCO. , , , , .

+2

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


All Articles