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

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

问题描述

我一直试图在JavaScript上下文中理解Tail call optimization,并为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是唯一支持尾叫优化的浏览器.

Chrome团队明确声明尾调用优化尚未处于积极开发中,可以被跟踪

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/tail-call-optimization.html

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

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