实例化包含已定义变量的类时出现性能问题



我注意到在实例化带有defined variablesclass时,Javascript中出现了一些奇怪的行为。

注意:下面的代码只是作为这个特定问题的复制案例。

让我们考虑以下类别:

class Vector3
{
#unused1;
#unused2;
#unused3;
#unused4;
#unused5;
#unused6;
#unused7;
#unused8;
#unused9;
#unused10;
#unused11;
#unused12;
#unused13;
constructor(x, y, z)
{
this.x = x;
this.y = y;
this.z = z;
}
}

以及以下脚本:

let frames = 0;
let p = 0;
let fn = () => {
let now = performance.now();
let sum;
for (let i = 0; i < 10000; i++) {
var vector = new Vector3(Math.random(),Math.random(),Math.random());
var o = new Vector3(vector.x + Math.random(), vector.y + Math.random(), vector.z + Math.random());
}
// check the amount of passed frames every second
if (now - p >= 1000) {
console.log(frames);
// added to also test performance without having Dev Tools open
document.documentElement.innerText = frames;
frames = 0;
p = now;
}
frames++;
requestAnimationFrame(() => {
return fn();
})
return;
}
fn();

当运行以上内容并查看控制台时,我们可以看到性能在左右(取决于您的规格(,30到35帧。

现在,如果我们修改类,使其不包含这样定义的变量:

class Vector3
{
constructor(x, y, z)
{
this.x = x;
this.y = y;
this.z = z;
}
}

我们可以看到性能达到(再次,取决于您的规格(60帧及以上。

起初,我认为这个问题与garbage collection有关,但在检查了Chrome Profiler后,我注意到大部分性能都被getting变量消耗掉了,在进一步的研究/基准测试后,我发现这个问题实际上与变量in use无关,而是与变元declared有关。

同样重要的是要注意;物质;如果变量被声明为CCD_ 8或CCD_。

有人能解释为什么会出现这个问题吗?

更新:此问题对Chromium的影响似乎大于对Firefox的影响。CCD_ 12";总是";似乎达到了60。

您强调的性能问题是初始化字段缓慢的未优化情况。它一直存在到Chrome 96。它现在已在2022年1月初发布的Chrome 97中修复。

这里有一些证据。

最新更新