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

Optimize a[n]; n++ inside loopings #8710

Open
rentalhost opened this issue Mar 8, 2024 · 2 comments
Open

Optimize a[n]; n++ inside loopings #8710

rentalhost opened this issue Mar 8, 2024 · 2 comments
Milestone

Comments

@rentalhost
Copy link

rentalhost commented Mar 8, 2024

Describe the feature

In cases where we manipulate a number using ++ or -- after its use, it may be possible to use it inline, reducing a few bytes (~2 bytes per use). Currently, this feature works outside of looping.

For instance:

const a = [1, 2, 3];
let n = 0;

while (n < a.length) {
  x(a[n]);
  n++;
}

Will be (prettified):

const a = [1, 2, 3];
let n = 0;

for (; n < a.length; )
  x(a[n]), n++;

Could be:

const a=[1,2,3];
let n=0;

for(;n<a.length;)
  x(a[n++]);

So n will be post-incremented, but it will return the old value to access the index at a anyway.

It is possible to think of other variations to this rule, although most cases will be simple like the first example.

const a = [1, 2, 3];

let n = 0;
let m = 0;

while (n + m < a.length) {
  x(a[n + m]); // after: x(a[n+++m++]
  n++;
  m++;
}
// My (almost) real case:
const a = [1, 2, 3, 4, 5];

let n = 0;
let m = 2;

while (m < a.length) {
  a[m] = a[n]; // after: a[m++] = a[n++]
  m++;
  n++;
}
// My real case:
const a = [1, 2, 3, 4, 5];

let m = 2;

while (m < a.length) {
  a[m] = a[m - 2]; // after: a[m] = a[m++-2]
  m++;
}

Note: currently Terser does not support this kind of optimization.

Babel plugin or link to the feature description

No response

Additional context

No response

@kdy1 kdy1 added this to the Planned milestone Mar 8, 2024
@magic-akari
Copy link
Member

magic-akari commented Mar 8, 2024

Here is a bad case:

const a = [1, 2, 3];
let n = 0;

const x = (i) => {
  if(n !== 0) {
    console.log("---");
  }
  console.log(i);
}

for (; n < a.length; )
  x(a[n]), n++;

Result:

1
---
2
---
3

"minified":

const a = [1, 2, 3];
let n = 0;

const x = (i) => {
  if(n !== 0) {
    console.log("---");
  }
  console.log(i);
}

for (; n < a.length; )
  x(a[n++]);

Result:

---
1
---
2
---
3

@rentalhost
Copy link
Author

You are right! Maybe it can check if function has scope greater then the variable.

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

No branches or pull requests

3 participants