Is this an optimization for explicitly initializing members of an undefined object in JavaScript, given knowledge of the internal affairs of V8 / spidermonkey / chakra?

In JavaScript, the widespread principle of good performance is to avoid changing the shape of the object.

It makes me wonder if it is

class Foo {
  constructor() {
    this.bar = undefined;
  }

  baz(x) { this.bar = x; }
}

good practice that will give better performance than this

class Foo {
  constructor() {
  }

  baz(x) { this.bar = x; }
}

How is this true or false? What for? And is this more or less true in one JS engine over others?

+4
source share
1 answer

V8 developer is here.

Yes, the first version is, in general, a good practice.

, . , , , - , , , , , .

, , , , Foo "", , .bar . , , JavaScript /, ; , .

:

class Foo() {
  constructor() {}
  addBar(x) { this.bar = x; }
  addBaz(x) { this.baz = x; }
  addQux(x) { this.qux = x; }
}
var foo1 = new Foo(); foo1.addBar(1);
var foo2 = new Foo(); foo2.addBaz(10); foo2.addBar(2);
var foo3 = new Foo(); foo3.addQux(100); foo3.addBaz(20); foo3.addBar(3);

function hot_function(foo) {
  return foo.bar;  // [1]
}
hot_function(foo1);
hot_function(foo2);
hot_function(foo3);

, [1], . JavaScript bar . , , , , , , undefined, Foo , bar , .

: , addBar() , , ( ), (, , ), ( , ).

, . , , .

, . , . !

+9

Source: https://habr.com/ru/post/1678911/


All Articles