Skip to content

Commit c47cf0a

Browse files
perf(minify): fold array and string enumeration (#22854)
* perf(minify): fold array and string enumeration * perf(minifier): preserve lexical reads when folding array keys * test(minify): update the snapshot of an unread `Object.keys` call now dropped Claude-Session: https://claude.ai/code/session_01ViD41i2KdwwGxrDk7yrjeD * test(minify): update the enumeration snapshots to main's double-quoted strings Claude-Session: https://claude.ai/code/session_01ViD41i2KdwwGxrDk7yrjeD * test(minify): list test262 keys.js, 1 B bigger gzipped once `Object.keys("foo")` folds Claude-Session: https://claude.ai/code/session_01ViD41i2KdwwGxrDk7yrjeD --------- Co-authored-by: alexander-akait <[email protected]>
1 parent d377393 commit c47cf0a

10 files changed

Lines changed: 254 additions & 21 deletions

File tree

‎lib/javascript/syntax-printer.js‎

Lines changed: 50 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -18549,8 +18549,11 @@ const installCorrect = (modules) => {
1854918549
if (
1855018550
A.isForInNode(parent) &&
1855118551
parent.right === child &&
18552+
// Inlining can copy the declaration node while keeping its definition.
1855218553
A.walk(parent.left, (/** @type {Node} */ node) =>
18553-
node === declaration ? A.walk_abort : undefined
18554+
A.isSymbolDeclarationNode(node) && node.definition === self.definition
18555+
? A.walk_abort
18556+
: undefined
1855418557
)
1855518558
) {
1855618559
return true;
@@ -24129,7 +24132,7 @@ const installImprove = (modules) => {
2412924132

2413024133
/**
2413124134
* `Object.keys({ a: 1 })` as `["a"]`, and `values` and `entries` alike, of
24132-
* an object literal of plain keys whose values have no effect.
24135+
* object, array and string literals whose values have no effect.
2413324136
* @param {Node} call an `Object` call terser has optimized
2413424137
* @param {Compressor} compressor the compressor
2413524138
* @returns {Node | undefined} the array literal, or undefined
@@ -24144,7 +24147,11 @@ const installImprove = (modules) => {
2414424147
!A.isSymbolRefNode(callee.object) ||
2414524148
callee.object.name !== "Object" ||
2414624149
args.length !== 1 ||
24147-
!A.isObjectNode(args[0]) ||
24150+
!(
24151+
A.isObjectNode(args[0]) ||
24152+
A.isArrayNode(args[0]) ||
24153+
A.isStringNode(args[0])
24154+
) ||
2414824155
!compressor.option("evaluate") ||
2414924156
!readsUnassignedGlobal(callee.object, compressor)
2415024157
) {
@@ -24157,24 +24164,48 @@ const installImprove = (modules) => {
2415724164
if (written === true || written.has(name)) return undefined;
2415824165
/** @type {Record<string, Node>} */
2415924166
const values = Object.create(null);
24160-
for (const property of args[0].properties) {
24161-
if (!A.isObjectKeyValNode(property) || property.computed) {
24162-
return undefined;
24167+
const argument = args[0];
24168+
if (A.isObjectNode(argument)) {
24169+
for (const property of argument.properties) {
24170+
if (!A.isObjectKeyValNode(property) || property.computed) {
24171+
return undefined;
24172+
}
24173+
const key = A.terserKey(property.key);
24174+
const { value } = property;
24175+
if (
24176+
(typeof key !== "string" && typeof key !== "number") ||
24177+
key === "__proto__" ||
24178+
// Engines once disagreed on where an integer key past 2 ** 32 - 2 sorts.
24179+
/^\d{10}/.test(String(key)) ||
24180+
A.hasSideEffects(/** @type {Node} */ (value), compressor) ||
24181+
// A function or class takes its name from the key it is defined at.
24182+
(name !== "keys" && (A.isLambdaNode(value) || A.isClassNode(value)))
24183+
) {
24184+
return undefined;
24185+
}
24186+
values[key] = /** @type {Node} */ (value);
2416324187
}
24164-
const key = A.terserKey(property.key);
24165-
const { value } = property;
24166-
if (
24167-
(typeof key !== "string" && typeof key !== "number") ||
24168-
key === "__proto__" ||
24169-
// Engines once disagreed on where an integer key past 2 ** 32 - 2 sorts.
24170-
/^\d{10}/.test(String(key)) ||
24171-
A.hasSideEffects(/** @type {Node} */ (value), compressor) ||
24172-
// A function or class takes its name from the key it is defined at.
24173-
(name !== "keys" && (A.isLambdaNode(value) || A.isClassNode(value)))
24174-
) {
24175-
return undefined;
24188+
} else if (A.isArrayNode(argument)) {
24189+
for (let index = 0; index < argument.elements.length; index++) {
24190+
const value = argument.elements[index];
24191+
if (value === null) continue;
24192+
if (
24193+
A.isExpansionNode(value) ||
24194+
A.hasSideEffects(value, compressor) ||
24195+
(name === "keys" && A.dropSideEffectFree(value, compressor))
24196+
) {
24197+
return undefined;
24198+
}
24199+
values[index] = value;
24200+
}
24201+
} else {
24202+
const text = /** @type {string} */ (argument.value);
24203+
// Boxed strings enumerate UTF-16 code units, not code points.
24204+
for (let index = 0; index < text.length; index++) {
24205+
values[index] = makeNode(A.StringNode, argument, {
24206+
value: text[index]
24207+
});
2417624208
}
24177-
values[key] = /** @type {Node} */ (value);
2417824209
}
2417924210
// The engine orders them: integer keys ascending, then the rest as defined.
2418024211
const elements = Object.keys(values).map((key) => {
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
2+
3+
exports[`ConfigCacheTestCases optimization minify-object-enumeration exported tests should enumerate a string's UTF-16 code units 1`] = `"function(){return[[\\"0\\",\\"1\\"],[\\"a\\",\\"b\\"],[[\\"0\\",\\"a\\"]],[\\"\\\\ud800\\"],[],[],[]]}"`;
4+
5+
exports[`ConfigCacheTestCases optimization minify-object-enumeration exported tests should enumerate array literals without reading holes or length 1`] = `"function(){return[[\\"0\\",\\"2\\"],[10,30],[[\\"0\\",10],[\\"2\\",30]],[],[],[]]}"`;
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
2+
3+
exports[`ConfigTestCases optimization minify-object-enumeration exported tests should enumerate a string's UTF-16 code units 1`] = `"function(){return[[\\"0\\",\\"1\\"],[\\"a\\",\\"b\\"],[[\\"0\\",\\"a\\"]],[\\"\\\\ud800\\"],[],[],[]]}"`;
4+
5+
exports[`ConfigTestCases optimization minify-object-enumeration exported tests should enumerate array literals without reading holes or length 1`] = `"function(){return[[\\"0\\",\\"2\\"],[10,30],[[\\"0\\",10],[\\"2\\",30]],[],[],[]]}"`;
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
it("should enumerate array literals without reading holes or length", () => {
2+
/** @returns {Array<Array<string | number | [string, number]>>} enumerated properties */
3+
function enumerate() {
4+
return [
5+
Object.keys([10, , 30]),
6+
Object.values([10, , 30]),
7+
Object.entries([10, , 30]),
8+
Object.keys([]),
9+
Object.values([, ,]),
10+
Object.entries([])
11+
];
12+
}
13+
expect(enumerate()).toEqual([
14+
["0", "2"],
15+
[10, 30],
16+
[["0", 10], ["2", 30]],
17+
[],
18+
[],
19+
[]
20+
]);
21+
expect(enumerate.toString()).toMatchSnapshot();
22+
});
23+
24+
it("should enumerate a string's UTF-16 code units", () => {
25+
/** @returns {Array<Array<string | [string, string]>>} enumerated properties */
26+
function enumerate() {
27+
return [
28+
Object.keys("\ud83d\ude00"),
29+
Object.values("ab"),
30+
Object.entries("a"),
31+
Object.values("\ud800"),
32+
Object.keys(""),
33+
Object.values(""),
34+
Object.entries("")
35+
];
36+
}
37+
expect(enumerate()).toEqual([
38+
["0", "1"],
39+
["a", "b"],
40+
[["0", "a"]],
41+
["\ud800"],
42+
[],
43+
[],
44+
[]
45+
]);
46+
expect(enumerate.toString()).toMatchSnapshot();
47+
expect(Object.values("\ud83d\ude00")).toEqual(["\ud83d", "\ude00"]);
48+
expect(Object.entries("ab")).toEqual([["0", "a"], ["1", "b"]]);
49+
});
50+
51+
it("should preserve array element values and anonymous function names", () => {
52+
const reference = {};
53+
/**
54+
* @template T
55+
* @param {T} value the first element
56+
* @returns {Array<T | (() => void) | (new () => object) | undefined>} the values
57+
*/
58+
function values(value) {
59+
return Object.values([value, function () {}, class {}, undefined]);
60+
}
61+
const result = values(reference);
62+
expect(result[0]).toBe(reference);
63+
expect(result[1].name).toBe("");
64+
expect(result[2].name).toBe("");
65+
expect(result[3]).toBeUndefined();
66+
});
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
it("should preserve array element effects and exceptions", () => {
2+
const calls = [];
3+
/**
4+
* @param {number} value the next value
5+
* @returns {number} the recorded value
6+
*/
7+
function record(value) {
8+
calls.push(value);
9+
return value;
10+
}
11+
expect(Object.keys([record(1), , record(2)])).toEqual(["0", "2"]);
12+
expect(Object.values([record(3), record(4)])).toEqual([3, 4]);
13+
expect(Object.entries([record(5)])).toEqual([["0", 5]]);
14+
expect(calls).toEqual([1, 2, 3, 4, 5]);
15+
expect(() => Object.keys([missingEnumerationValue])).toThrow(ReferenceError);
16+
});
17+
18+
it("should preserve array element reads before a let declaration", () => {
19+
expect(() => Object.keys([value])).toThrow(ReferenceError);
20+
let value;
21+
});
22+
23+
it("should preserve array element reads before a const declaration", () => {
24+
expect(() => Object.keys([value])).toThrow(ReferenceError);
25+
const value = 1;
26+
});
27+
28+
it("should preserve typeof before a lexical declaration", () => {
29+
expect(() => Object.keys([typeof value])).toThrow(ReferenceError);
30+
let value;
31+
});
32+
33+
it("should preserve reads of a loop binding in its own iterable", () => {
34+
expect(() => {
35+
for (let value of Object.keys([value])) expect(value).toBeDefined();
36+
}).toThrow(ReferenceError);
37+
});
38+
39+
it("should preserve iteration when enumerating an array with a spread", () => {
40+
let iterations = 0;
41+
const iterable = {
42+
*[Symbol.iterator]() {
43+
iterations++;
44+
yield 4;
45+
yield 5;
46+
}
47+
};
48+
expect(Object.keys([...iterable])).toEqual(["0", "1"]);
49+
expect(Object.values([...iterable])).toEqual([4, 5]);
50+
expect(Object.entries([...iterable])).toEqual([["0", 4], ["1", 5]]);
51+
expect(iterations).toBe(3);
52+
});
53+
54+
it("should keep shadowed Object methods and unsupported inputs", () => {
55+
/**
56+
* @param {{keys: (value: number[]) => number, values: (value: string) => number, entries: (value: never[]) => number}} Object the shadowed methods
57+
* @returns {number[]} their results
58+
*/
59+
function shadow(Object) {
60+
return [Object.keys([1]), Object.values("a"), Object.entries([])];
61+
}
62+
expect(shadow({ keys: () => 1, values: () => 2, entries: () => 3 })).toEqual([
63+
1, 2, 3
64+
]);
65+
expect(() => Object.keys(null)).toThrow(TypeError);
66+
expect(() => Object.values(undefined)).toThrow(TypeError);
67+
expect(Object.entries(1)).toEqual([]);
68+
});
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
it("should preserve replaced Object enumeration methods", () => {
2+
const keys = Object.keys;
3+
const values = Object.values;
4+
const entries = Object.entries;
5+
try {
6+
Object.keys = () => ["keys"];
7+
Object.values = () => ["values"];
8+
Object.entries = () => ["entries"];
9+
const result = [
10+
Object.keys([1]), Object.keys("a"),
11+
Object.values([1]), Object.values("a"),
12+
Object.entries([1]), Object.entries("a")
13+
];
14+
Object.keys = keys;
15+
Object.values = values;
16+
Object.entries = entries;
17+
expect(result).toEqual([
18+
["keys"], ["keys"], ["values"], ["values"], ["entries"], ["entries"]
19+
]);
20+
} finally {
21+
Object.keys = keys;
22+
Object.values = values;
23+
Object.entries = entries;
24+
}
25+
});
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"use strict";
2+
3+
const MinimizerPlugin = require("minimizer-webpack-plugin");
4+
const jsMinify = require("../../../../lib/javascript/jsMinify");
5+
6+
/** @type {import("../../../../").Configuration[]} */
7+
module.exports = ["constants", "effects", "mutated"].map((name, index) => ({
8+
mode: "production",
9+
target: ["web", "es2018"],
10+
entry: `./${name}.js`,
11+
experiments: { futureDefaults: true },
12+
output: { filename: `bundle${index}.js`, module: false },
13+
optimization: {
14+
minimize: true,
15+
minimizer: [
16+
new MinimizerPlugin({
17+
// Keep coverage counters in the process running the tests.
18+
parallel: false,
19+
minify: jsMinify,
20+
minimizerOptions: {
21+
ecma: 2018,
22+
mangle: false,
23+
compress: { passes: 2 },
24+
format: { ascii_only: true }
25+
}
26+
})
27+
]
28+
}
29+
}));

‎test/specCases/minify-corpora.spectest.js‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1833,6 +1833,10 @@ for (const [reason, keys] of /** @type {[string, string[]][]} */ ([
18331833
"yield-promise-reject-next-for-await-of-sync-iterator.js (the default minimizer's options)",
18341834
"yield-promise-reject-next-yield-star-async-iterator.js (the default minimizer's options)"
18351835
]
1836+
],
1837+
[
1838+
"`Object.keys` of a string literal folded into the array it returns, where gzip matched the repeated call",
1839+
["keys.js (the default minimizer's options)"]
18361840
]
18371841
])) {
18381842
for (const key of keys) IMPROVED_YET_BIGGER[key] = reason;

‎test/unitCases/javascript/__snapshots__/printer.unittest.js.snap‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -713,7 +713,7 @@ exports[`syntax-printer improve phase should write less, printing the same: argu
713713

714714
exports[`syntax-printer improve phase should write less, printing the same: assignments opening the statement after a \`var\`, as its values 1`] = `"var k;function f(o){var a,b;console.log(a=o.x,b=o.y,a,b)}function g(o){var a;return console.log(a=o.x,a),a}function h(o){var a=o.x;return k=function(){return a}}function m(o){var a=o.x;try{console.log(a)}finally{console.log(a+1)}}f({x:1,y:2}),h({x:4}),m({x:5}),console.log(g({x:3}),k());"`;
715715

716-
exports[`syntax-printer improve phase should write less, printing the same: built-in calls and constructions on literals no one reads 1`] = `"Object.keys([1,,2]),console.log(1);"`;
716+
exports[`syntax-printer improve phase should write less, printing the same: built-in calls and constructions on literals no one reads 1`] = `"console.log(1);"`;
717717

718718
exports[`syntax-printer improve phase should write less, printing the same: built-in globals and their properties no one reads 1`] = `"console.log(1);"`;
719719

‎test/unitCases/javascript/printer.unittest.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2076,7 +2076,7 @@ const KEPT_CASES = [
20762076
["a RegExp pattern not a string", 'try { RegExp(1); console.log(1); } catch (e) { console.log(2); }'],
20772077
["a function returning a call in place of a function reading its own `this`, naming itself, holding a directive or declaring a parameter's name", 'var o = { m: function () { return function () { for (var i = 0; i < 2; i++) console.log(typeof this, i); }(); } }; o.m(); var f = function () { return function g() { for (var i = 0; i < 2; i++) console.log(typeof g, i); }(); }; f(); var h = function () { return function () { "use strict"; for (var i = 0; i < 2; i++) console.log(typeof this, i); }(); }; h(); var k = function (a) { return function () { for (var a in { x: 1, y: 2 }) console.log(a); }(); }; k(1);'],
20782078
["a count too large to run", 'try { new Uint8Array(1e9); console.log(1); } catch (e) { console.log(2); }'],
2079-
["an argument no literal", "function f(a) { String(a); Object.keys({ [a]: 1 }); Object.keys({ get b() { return 1; } }); Object.keys({ __proto__: a }); Object.keys([a]); Object.keys({ b: a }, 0); } f([1]); console.log(1);"],
2079+
["an argument no literal", "function f(a) { String(a); Object.keys({ [a]: 1 }); Object.keys({ get b() { return 1; } }); Object.keys({ __proto__: a }); Object.keys(a); Object.keys({ b: a }, 0); } f([1]); console.log(1);"],
20802080
["a built-in that runs code", 'eval("console.log(1)");'],
20812081
["a built-in global the program declares", "var Set = function () { console.log(1); }; new Set();"],
20822082
["a built-in call a `with` could rebind", "with ({ JSON: { parse: function () { console.log(1); } } }) JSON.parse(\"1\");"],

0 commit comments

Comments
 (0)