JavaScript 尾调用中的函数是否经过优化? [英] Are functions in JavaScript tail-call optimized?

查看:35
本文介绍了JavaScript 尾调用中的函数是否经过优化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图在 JavaScript 上下文中理解 尾调用优化,并为 factorial() 编写了以下递归和尾递归方法.

I have been trying to understand Tail call optimization in context of JavaScript and have written the below recursive and tail-recursive methods for factorial().

递归:

function factorial (n) {
  if (n < 2) {
    return 1;
  } else {
    return n * factorial(n-1);
  }
}

尾递归:

function factorial (n) {
  function fact(n, acc) {
    if (n < 2) {
      return acc;
    } else {
      return fact(n-1, n * acc);
    }
  }

  return fact(n, 1)
}

但我不确定函数的 tail-recursive 版本是否会像在其他语言(如 Scala 等)中一样由 JavaScript 编译器优化.有人可以帮我解决这个问题吗?

But I am not sure if the tail-recursive version of the function will be optimised by JavaScript compiler as it is done in other languages like Scala etc. Can someone help me out on this one?

推荐答案

更新:截至 2020 年 1 月 1 日,Safari 是唯一支持尾调用优化的浏览器.

chromium 团队明确表示,Tail Call Optimization 未在积极开发中,可以跟踪 此处.

The chromium team explicitly states that Tail Call Optimization is not under active development and can be tracked here.

可以在此处

原帖

是的,ES2015 在严格模式下提供尾调用优化.Axel Rauschmayer 博士在下面的链接中对其进行了精美的展示,因此我不会在这里重复他的话.

Yes, ES2015 offers tail call optimization in strict mode. Dr. Axel Rauschmayer lays it out beautifully at the link below so I shall not repeat his words here.

注意:ES 5 没有优化尾调用.

Note: ES 5 does not optimize tail calls.

http://www.2ality.com/2015/06/尾调用优化.html

这篇关于JavaScript 尾调用中的函数是否经过优化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆