Home > Enterprise >  Does Google Apps Script (GAS) support proper tail calls or tail call optimization?
Does Google Apps Script (GAS) support proper tail calls or tail call optimization?

Time:04-18

I'm wondering whether investing time into doing tail call optimization for a Google Apps Script is worth it.

So, I've understood that Google Apps Script uses the ES2015 (ES6) version of the JavaScript specification (ref1, ref2), running it on the V8 runtime implementation.

Supposedly, ES2015 supports (proper) tail call optimization from the spec. But there are some indications that V8 actually doesn't implement it:

Furthermore, I've learned there is an important nuance here:

The terminology of proper tail calls (PTC) and tail call optimization (TCO) is often conflated. Here's the difference between the two:

  • proper tail calls: functions called in the tail position reuse the current stack frame, preventing the creation of additional stack frames that cause space inefficiency.
  • tail call optimization: rewrites a recursive function into an iterative one, usually by calling goto.

PTC only deals with stack manipulation, while TCO rewrites a recursive function as an iterative function.

So, given this...

Does Google Apps Script (GAS):

  • support proper tail calls? My guess from the above is "No.", but it'd be nice to have an authoritative answer, as far as possible.
  • support tail call optimization to the point where it is worth doing it, for performance, in any way? My guess is "Yes, you can do it, but it doesn't improve performance." But it'd be nice if someone knew it definitively, or could point to a GAS performance comparison that demonstrates it.

CodePudding user response:

(V8 developer here.)

Does Google Apps Script (GAS) support proper tail calls?

No. V8 does not support PTCs (nor STCs); you've already linked to the background story yourself. Since GAS is built on V8 for JS execution, it can't support them either.

wondering whether investing time into doing tail call optimization for a script is worth it. / Does GAS support tail call optimization to the point where it is worth doing it, for performance, in any way?

I'm not sure what you mean: TCO is something that a compiler potentially does, not something you do.

If you mean "moving calls into tail positions, so the compiler can turn them into iterations": No, V8 doesn't do that, so that's not worth your time. Whether a call occurs in a tail position or not makes no difference for performance. (And I wouldn't bet on that changing any time soon.)

If you mean "manually converting recursion into iteration": that may be worth doing for performance-critical code; whether it's worth doing in your particular case can only be answered by trying it and measuring the effect. (As always, a small artificial test a.k.a. "microbenchmark" is very likely to produce misleading results that don't apply to other situations.)
This doesn't need any "support" from GAS or V8.

  • Related