JavaScript 尾调用中的函数是否经过优化?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37224520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:03:12  来源:igfitidea点击:

Are functions in JavaScript tail-call optimized?

javascriptrecursiontail-recursion

提问by Aditya Singh

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

我一直试图Tail call optimization在 JavaScript 的上下文中理解,并为factorial().

Recursive:

递归:

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

Tail-recursive:

尾递归:

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

  return fact(n, 1)
}

But I am not sure if the tail-recursiveversion 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?

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

采纳答案by sheeldotme

Update: As of January 1, 2020 Safari is the only browser that supports tail call optimization.

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

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

Chromium 团队明确指出,Tail Call Optimization 未在积极开发中,可以在此处进行跟踪。

The implementation for Firefox can be tracked here

可以在此处跟踪 Firefox 的实现

Original Post

原帖

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.

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

Note: ES 5 does not optimize tail calls.

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

http://www.2ality.com/2015/06/tail-call-optimization.html

http://www.2ality.com/2015/06/tail-call-optimization.html

回答by AK_

In theory yes. As the other answer states.

理论上是的。正如另一个答案所述。

In practice though, as of July 2017, No. Only Safari supports it.

但实际上,截至 2017 年 7 月,否。只有 Safari 支持它。

Javascript ES6 (ES2015) compatability: https://kangax.github.io/compat-table/es6/

Javascript ES6 (ES2015) 兼容性:https://kangax.github.io/compat-table/es6/