Skip to content

Array constructor with length is not eliminated #4046

@KimlikDAO-bot

Description

@KimlikDAO-bot
Contributor

Consider the code:

/** @const {!Array<number>} */
const a = [1];

/** @const {!Array<number>} */
const b = Array(10);
b[0] = 2;

/** @const {!Array<number>} */
const c = [];
c.push(3);

/** @const {!Array<number>} */
const d = Array(10);
d.push(4);

When compiled with

yarn google-closure-compiler -O ADVANCED --js a.js --rewrite_polyfills=false 

we get

Array(10)[0]=2;Array(10).push(4);

Arrays created with the Array(len) constructor are not eliminated.

google-closure-compiler version: v20230103

Activity

brad4d

brad4d commented on Jan 23, 2023

@brad4d
Contributor

The peephole optimizations remove the cases of an array created with an array literal.

Presumably we could update whichever one does that so it also removes arrays created with the Array() constructor.

However, I don't think we're likely to prioritize fixing this.
It's just not likely to be worth the effort.

I'll mark this as "help wanted", since I think it would be a good small contribution that could be made from outside our team.

KimlikDAO-bot

KimlikDAO-bot commented on Jan 23, 2023

@KimlikDAO-bot
ContributorAuthor

Thank you! We'll look into fixing this

jobedrony

jobedrony commented on Aug 6, 2023

@jobedrony

I want to work in this issue

PTheocharis

PTheocharis commented on Mar 15, 2024

@PTheocharis

Is it possible I work on this issue?

KimlikDAO-bot

KimlikDAO-bot commented on May 29, 2024

@KimlikDAO-bot
ContributorAuthor

@brad4d Could you point to some relevant files in the code?

brad4d

brad4d commented on Jun 4, 2024

@brad4d
Contributor

I would start by adding a test case here:

fold("new Array(10);", "");

Then investigate how to make PeepholeRemoveDeadCode pass this test.

KimlikDAO-bot

KimlikDAO-bot commented on Mar 2, 2025

@KimlikDAO-bot
ContributorAuthor

@brad4d Actually that test passes. The difference between [] and Array() constructor is only visible if we do something like [undefined].push(1) vs Array(1).push(1).

brad4d

brad4d commented on Mar 7, 2025

@brad4d
Contributor

In that case, you should start with a test case containing those two cases and use the debugger to investigate what it is that prevents the Array(1).push(1); from being removed but allows [undefined].push(1); to be removed.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @brad4d@KimlikDAO-bot@PTheocharis@jobedrony

        Issue actions

          Array constructor with length is not eliminated · Issue #4046 · google/closure-compiler