Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Minification] Hoist static methods with alias #9741

Open
SukkaW opened this issue Nov 16, 2024 · 2 comments
Open

[Minification] Hoist static methods with alias #9741

SukkaW opened this issue Nov 16, 2024 · 2 comments
Milestone

Comments

@SukkaW
Copy link
Contributor

SukkaW commented Nov 16, 2024

Describe the feature

Given the following code:

const a = {};
Object.assign(a, {});
const b = {};
Object.assign(b, {});
Object.assign(b, a);

Currently both terser and swc can only minified the code into

const a={};Object.assign(a,{});const b={};Object.assign(b,{}),Object.assign(b,a);

Here is my proposal, a new compress option unsafe_hoist_static_method_alias. In the compress phase, swc counts and replaces static built-in object methods with aliases:

const __ObjectAssign = Object.assign;

const a = {};
__ObjectAssign(a, {});
const b = {};
__ObjectAssign(b, {});
__ObjectAssign(b, a);

In the mangle phase, swc can mangle __ObjectAssign into a shorter name:

const s=Object.assign,c={};s(c,{});const n={};s(n,{}),s(n,c);

Note that this optimization should only applied to built-in objects' known static methods (Object.assign, Reflect.apply, etc.). Also since it is possible for user code to override built-in objects' static methods, this option should be prefixed with unsafe and should not be enabled by default.

Babel plugin or link to the feature description

No response

Additional context

No response

@kdy1 kdy1 added this to the Planned milestone Nov 16, 2024
@kdy1
Copy link
Member

kdy1 commented Nov 16, 2024

I like the idea, although I'm not sure if how many users are using unsafe_ options.

This operation should be done by precompress pass at https://github.com/swc-project/swc/blob/d437fd8283e689101e6e783040cab7f4f277a324/crates/swc_ecma_minifier/src/pass/precompress.rs

@SukkaW
Copy link
Contributor Author

SukkaW commented Nov 16, 2024

We can hoist built-in objects as well:

const mapA = new Map();
const mapB = new Map();
const mapC = new Map();
const mapD = new Map();

console.log(mapA, mapB, mapC, mapD);

Currently this can only be minified into:

const n=new Map;console.log(n,new Map,new Map,new Map);

But if we alias Map to a variable:

const __Map = Map;

const mapA = new __Map();
const mapB = new __Map();
const mapC = new __Map();
const mapD = new __Map();

console.log(mapA, mapB, mapC, mapD);

Now the minified version:

const n=Map,e=new n;console.log(e,new n,new n,new n);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

2 participants