Initializing object properties with null
suggest changeJavaScript engines optimize property access when objects keep a stable shape. This is the idea behind the old MDN note on hidden classes.
Fortunately, the objects and properties are often “predictable”, and in such cases their underlying structure can also be predictable. JITs can rely on this to make predictable accesses faster.
Defining every property in the constructor keeps that shape stable. If a property will be filled in later, initializing it with null avoids adding a new property on only some instances. Engines differ, and the gain is not guaranteed. Current optimizing compilers also handle later property additions better than older ones did.
The following microbenchmark builds a large array of objects and sometimes adds x after construction. f2 declares x up front. The timings below are one old sample from Firefox and Chrome, not a current measurement. performance.now() is available in browsers and in modern Node.
This is code:
function f1() {
const P = function () {
this.value = 1
};
const big_array = new Array(10000000).fill(1).map((x, index)=> {
const p = new P();
if (index > 5000000) {
p.x = "some_string";
}
return p;
});
big_array.reduce((sum, p)=> sum + p.value, 0);
}
function f2() {
const P = function () {
this.value = 1;
this.x = null;
};
const big_array = new Array(10000000).fill(1).map((x, index)=> {
const p = new P();
if (index > 5000000) {
p.x = "some_string";
}
return p;
});
big_array.reduce((sum, p)=> sum + p.value, 0);
}
(function perform(){
let start = performance.now();
f1();
let duration = performance.now() - start;
console.log('duration of f1 ' + duration);
start = performance.now();
f2();
duration = performance.now() - start;
console.log('duration of f2 ' + duration);
})()
This is the result for Chrome and Firefox.
FireFox Chrome
--------------------------
f1 6,400 11,400
f2 1,700 9,600
As we can see, the performance improvements are very different between the two.