开发者

Are any JavaScript engines tail call (TCO) optimized? [duplicate]

开发者 https://www.devze.com 2023-01-15 08:07 出处:网络
This question already has answers here: 开发者_运维知识库 Are functions in JavaScript tail-call optimized?
This question already has answers here: 开发者_运维知识库 Are functions in JavaScript tail-call optimized? (4 answers) Closed last month.

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.


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.


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


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


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 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号