for-of IteratorClose transpilation (a60744c) adds ~5% to ES5 bundle size, even for typed Arrays
Commit a60744c753 ("Fix Es6ForOfConverter to emit IteratorClose on abrupt completions") first shipped in v20260920. We understand it fixes real spec compliance, but it caused a large size regression for us, and we'd like to ask for a way to reduce or avoid it.
In Shaka Player, upgrading from v20260819 to v20260920, with no source changes, grew our ES5 bundles by 30 to 53 kB each. For our main bundle (ADVANCED, --language_out ECMASCRIPT5), that's +45 kB raw (+5.3%) and +11.5 kB gzipped (+4.1%). Our ES2021 bundles did not change. The same 39 polyfills are injected in both versions; the growth comes from the ~750 for-of loops in the library, each of which is now wrapped in try/finally. We have pinned v20260819 for now.
Input:
function sum(arr) { let total = 0; for (const x of arr) { total += x; } return total; }
window["sum"] = sum;v20260819 (-O SIMPLE --language_out ECMASCRIPT5):
function sum(a) {
var b = 0;
a = (0,$jscomp.makeIterator)(a);
for (var c = a.next(); !c.done; c = a.next()) {
b += c.value;
}
return b;
}v20260920:
function sum(a) {
var b = 0;
a = (0,$jscomp.makeIterator)(a);
var c = a.next(), d;
try {
for (; !c.done; c = a.next()) {
b += c.value;
}
} finally {
c && !c.done && (d = a.return) && d.call(a);
}
return b;
}In ADVANCED mode, with arr typed as !Array<number>, the try/finally is still emitted, although array iterators (native ones and $jscomp.arrayIterator) never have a return() method.
Any of these would help:
- Skip IteratorClose when the iterable is known to be an Array, TypedArray, or string. Their iterators have no
return(), so thefinallyblock can never do anything. In our code, most loops are over arrays. - Move the per-loop logic into a shared
$jscomphelper, e.g.$jscomp.iteratorClose(iter, result). The runtime would contain one copy, and each loop would pay only for a short call. - Add an option to opt out, like TypeScript without
downlevelIterationor Babel'sassumptions, for projects that don't depend on early-exitreturn()behavior.
Source: google/closure-compiler