Are any JavaScript engines tail call (TCO) optimized?

后端 未结 6 1293
有刺的猬
有刺的猬 2020-11-27 03:02

I have a tail recursive pathfinding algorithm that I\'ve implemented in JavaScript and would like to know if any (all?) browsers would possibly get stack overflow exceptions

相关标签:
6条回答
  • 2020-11-27 03:42

    Tail call optimization is now available in LispyScript which compiles to JavaScript. You can read more about it here.

    0 讨论(0)
  • 2020-11-27 03:42

    Currently no JavaScript implementations recognise tail recursion. Changes are being made in ECMAScript 6, and as others have said, there is an open ticket on V8.

    Here you can see V8's generated assembler for a tail recursion function:

    Example of how V8 compiles recursion

    Compare that to how Clang has compiled the same function in C

    Example of C compiler tail recursion

    V8 retains the recursive call, whereas the C compiler has recognised the tail recursion and changed it into a loop.

    0 讨论(0)
  • 2020-11-27 03:43

    No joy for the moment, but thankfully proper tail calls are slated for Harmony (ECMAScript version 6) http://wiki.ecmascript.org/doku.php?id=harmony:proper_tail_calls

    0 讨论(0)
  • 2020-11-27 03:45

    Tail call optimization will be supported In ECMAScript 6 strict mode in the future. Check http://www.2ality.com/2015/06/tail-call-optimization.html for details.

    Check http://kangax.github.io/compat-table/es6/ for current engine support.

    At the moment (18-07-2019) the following engines support tail call optimization:

    • Safari >= 10
    • iOS >= 10
    • Kinoma XS6
    • Duktape 2.3

    support if "experimental JavaScript features"-flag is turned on:

    • Node 6.5
    • Chrome 54 / Opera 41 Current version of the compat table does not list it anymore
    0 讨论(0)
  • 2020-11-27 03:54

    Pretty much every browser you encounter will barf on "too much recursion". Here's an entry in the V8 bug tracker that will probably be interesting reading.

    If it's simple self-recursion, it's probably worth the effort to use explicit iteration rather than hoping for tail-call elimination.

    0 讨论(0)
  • 2020-11-27 04:07

    The ECMAScript 4 specification was originally going to add support for TCO, but it was dropped:

    No more tail calls in JavaScript?

    As far as I know, no widely-available implementations of JavaScript currently do automatic TCO. This may be of use to you, though:

    Tail Call Optimization

    Essentially, using the accumulator pattern accomplish the same effect.

    0 讨论(0)
提交回复
热议问题