为什么没有javascript引擎支持尾调优化? [英] Why do no javascript engines support tail call optimization?

查看:96
本文介绍了为什么没有javascript引擎支持尾调优化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在Haskell中了解了尾部调用优化。我从以下帖子中了解到这不是javascript的一个功能:

I recently learned about tail call optimization in Haskell. I've learned from the following posts that this is not a feature of javascript:

  • Tail Recursion optimization for JavaScript?
  • Are any Javascript engines tail call optimized?

javascript的设计有什么固有的东西让尾调用优化特别困难吗?为什么这是像haskell这样的语言的主要特征,但现在才被讨论为某些javascript引擎的特性?

Is there something inherent to javascript's design that makes tail call optimization especially difficult? Why is this a main feature of a language like haskell, but is only now being discussed as a feature of certain javascript engines?

推荐答案

JavaScript支持尾调用优化。没有任何浏览器实现它,但它随着规范(ES2015)的最终确定而来,所有环境都将来实现它。像BabelJS这样将新JavaScript转换为旧JavaScript的运营商已经支持它,你今天就可以使用它。

Tail call optimisation is supported in JavaScript. No browsers implement it yet but it's coming as the specification (ES2015) is finalized and all environments will have to implement it. Transpilers like BabelJS that translate new JavaScript to old JavaScript already support it and you can use it today.

Babel的翻译非常简单:

The translation Babel makes is pretty simple:

function tcoMe(x){
    if(x === 0) return x;
    return tcoMe(x-1)
}

转换为:

function tcoMe(_x) {
    var _again = true;

    _function: while (_again) {
        var x = _x;
        _again = false;

        if (x === 0) return x;
        _x = x - 1;
        _again = true;
        continue _function;
    }
}

那是 - 到一个while循环。

That is - to a while loop.

至于为什么它只支持,社区中没有一个很大的需要来更快地这样做,因为它是带有循环的命令式语言,因此对于绝大多数情况,您可以自己编写此优化(不像需要这样的ML,如Bergi指出的那样)。

As for why it's only newly supported, there wasn't a big need from the community to do so sooner since it's an imperative language with loops so for the vast majority of cases you can write this optimization yourself (unlike in MLs where this is required, as Bergi pointed out).

这篇关于为什么没有javascript引擎支持尾调优化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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