Getting class instance property to inline

33 views
Skip to first unread message

Christian Lewis

unread,
Oct 22, 2020, 7:29:47 PM10/22/20
to Closure Compiler Discuss

I am wanting to lean on AOT array/string compilation for a library I’m working on, but I can’t get properties on this to inline even if manually flagged as @const.

/**
 * Initialize an empty array on `this.styles` and add to it during `build()`.
 */
class TestClass {
  constructor() {
    /** @const  {Array<string!>!} */
    this.styles = [];
  }

  build() {
    this.styles.push(...[
      '1',
      '2',
      '3',
    ]);
    return this;
  }

  dumpStyles() {
    console.log(
        'I won\'t inline:',
        this.styles.join(';'),
    );

    const inScopeStyles = [ '1', '2', '3' ];
    console.log(
        'I will:',
        inScopeStyles.join(';'),
    );
  }
}

new TestClass().build().dumpStyles();

Compiles to (with -O ADVANCED):

var a = new function() {
  this.a = [];
};
a.a.push.apply(a.a, ["1", "2", "3", ]);
console.log("I won't inline:", a.a.join(";"));
console.log("I will:", "1;2;3");

Any idea how to force the compiler to inline this.styles? Any help is much appreciated.

Christian Lewis

unread,
Oct 22, 2020, 7:43:01 PM10/22/20
to Closure Compiler Discuss

It appears the compiler actually notices the Array.push call and refuses to inline the array, even if it is const. I see this discussion about a potential @inline flag, but it does not seem like it was ever added.

If anyone has any advice for me here, it would be appreciated. It’s not the end of the world, but the state of this.styles is totally deterministic and it could be inlined without issue ideally.

Laura Harker

unread,
Oct 23, 2020, 11:40:03 AM10/23/20
to Closure Compiler Discuss
Unfortunately the compiler can't inline instance properties assigned in a constructor unless they are assigned immutable values.

Agree your case is statically analyzable (under the assumptions the compiler makes at least) but Closure Compiler doesn't know how to analyze it. The compiler is much better at inlining variables than it is properties.
Reply all
Reply to author
Forward
0 new messages