Search code examples
javascripttypescriptgoogle-chromev8tail-recursion

Tail recursion optimized javascript code performance worse than non optimization, it's counterintuitive,Is it because the compiler doesn't optimize?


function factorialNormal(n) {
  if (n === 1) {
    return n
  }
  return n + factorialNormal(n - 1)
}
function factorialWithTail(n, acc) {
  if (n === 1) return acc;
  return factorialWithTail(n-1, n + acc)
}

recursion function is fast than tail-recursion and the tail use more memory, causing the maximum call stack

enter image description here

Detailed answer here: ES6 Tail Recursion Optimisation Stack Overflow


Solution

  • There is no TCO on V8 currently.

    Here is the tracking ticket for this feature.