Question for v8 experts.
I noticed, that array literals instantiation seems to be very un-optimized, compared to the class instantiation. This is very weird, since constructing class instance involves executing constructor code - and array literals do not need to execute any code and can be allocated very efficiently. I wonder if I'm missing something obvious.
The results I receive in Node 16:
nickolay@frontier:~/workspace/typescript/monopoly$ nvm exec 16 node -r esm --expose-gc src_js/instantiation.js
Running node v16.4.1 (npm v7.18.1)
Garbage collection available.
Instantiate object: 1.325ms ±0.017 i:6 c:328
Instantiate array: 3.303ms ±0.077 i:6 c:138
Array literal performs 2.5 times worse!!
The 1st benchmark exercises the instantiation of this simple class:
class DataType0 {
constructor () {
this.prop00 = object
this.prop01 = 0
this.prop02 = '0'
this.prop03 = false
this.prop04 = true
this.prop05 = object
this.prop06 = 0
this.prop07 = 'true'
this.prop08 = false
this.prop09 = 0
this.prop10 = 0
this.prop11 = 0
this.prop12 = 0
this.prop13 = 0
this.prop14 = 0
this.prop15 = 0
}
}
The 2nd benchmark exercises the instantiation of the array literal with identical elements:
[
object,
0,
'0',
false,
true,
object,
0,
'true',
false,
0,
0,
0,
0,
0,
0,
0,
]
The allocation function looks like this:
//------------------------------------------------------------------------------
const size = 30000;
const generateObject = () => {
const instances = [];
do {
instances.push(__ALLOCATION_CALL_HERE__);
} while (instances.length < size);
return instances;
};
I'd expect the array literal instantiation to perform much better, since it does not need to execute any code and can be allocated with memory copy + some GC tracking. At the very least, I'd expect the array literal to perform on par with class instantiation.
The reason I'm instantiation the 16 properties, is that I read somewhere that in v8 every newly allocated array receives space for 16 elements.
To reproduce:
- Clone this repo:
git@github.com:canonic-epicure/monopoly.git - Inside the repo folder, run in console:
> npm i
> npx tsc
- Run in console:
> node -r esm --expose-gc src_js/instantiation.js
The benchmark file is: src_js/instantiation.js
Question: Am I missing something obvious (and there's a way to instantiate an array more efficiently), or this is indeed a "slow path" in v8?