简体   繁体   中英

Are any JavaScript engines tail call (TCO) optimized?

我有一个用 JavaScript 实现的尾递归寻路算法,想知道是否有任何(所有?)浏览器可能会出现堆栈溢出异常。

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.

暂时没有快乐,但幸运的是,Harmony(ECMAScript 版本 6)有适当的尾调用http://wiki.ecmascript.org/doku.php?id=harmony:proper_tail_calls

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.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM