javascriptrecursiones6-promisecontinuation-passing

Why would wrapping recursive function in promise improves the performance?


I was playing around with recursion and looking at the benchmark of different implementation.

function plusOne(xs) {
  if (xs.length <= 0) return []
  return [xs[0], ...plusOne(xs.slice(1))]
}


function plusOne2(xs) {
  if (xs.length <= 0) return Promise.resolve([])
  return plusOne2(xs.slice(1)).then(result => [xs[0] + 1, ...result])
}

function plusOne3(xs, cb) {
  if (xs.length <= 0) return cb([])
  return plusOne3(xs.slice(1), result => cb([xs[0], ...result]))
}

I notice the performance improved in the second implementation when I simply wrap the result in promise. I wonder why would it be the case.

Also in the third implementation, shouldn't the browser be able to do tail call optimisation with this continuation passing style? Why is it the slowest instead?

See perf.link


Solution

  • You are not waiting for those promises to finish.

    Try this:

    async function plusOne(xs) {
      if (xs.length <= 0) return []
      return [xs[0] + 1, ... await plusOne(xs.slice(1))]
    }
    
    
    await plusOne(xs)