swc-project / swc

Rust-based platform for the Web
https://swc.rs
Apache License 2.0
30.95k stars 1.21k forks source link

Transform static method calls into consts #7048

Open rentalhost opened 1 year ago

rentalhost commented 1 year ago

Describe the feature

In case where static method calls can be simplified to const.

For instance:

export const example = (x) =>
  Math.min([
    Math.max(1, x),
    Math.max(2, x)
  ]);

Could be transformed into:

const Math_max = Math.max;

export const example = (x) =>
  Math.min([
    Math_max(1, x),
    Math_max(2, x)
  ]);

With mangle top level:

let t = Math.max;

export const example = (x) =>
  Math.min([
    t(1, x),
    t(2, x)
  ]);

Note that only Math.max() is affected, as it occurs multiple times. However, there is a ~20% performance gain, so we can do the same for Math.min():

const Math_min = Math.min;
const Math_max = Math.max;

export const example = (x) =>
  Math_min([
    Math_max(1, x),
    Math_max(2, x)
  ]);

With mangle top level:

const t = Math.min;
const a = Math.max;

export const example = (x) =>
  t([
    a(1, x),
    a(2, x)
  ]);

My suggestion is create as a new option for "compress" group, but disabled by default. Or then a way to check when is advantage do that automatically.

Babel plugin or link to the feature description

No response

Additional context

No response

Knagis commented 1 year ago

There is a significant con to doing this - in JS every builtin can be overridden (Math.max = somePolyfill).