Object.defineProperty() 和 Object.defineProperties() 之间的性能差异

Performance difference between Object.defineProperty() and Object.defineProperties()

我正在寻找这两种方法之间的主要区别。

一些网站提到了可读性问题,但我的担忧主要与性能有关。似乎 defineProperty() 更快,但我找不到原因。

var FOR_TIME = 10000;


console.time("prop");
for(var i = 0; i < FOR_TIME; i++) {
    var test = {};
    Object.defineProperty(test, "ba", {});
    Object.defineProperty(test, "bab", {});
    Object.defineProperty(test, "bac", {});
}
console.timeEnd("prop");

console.time("props");
for(var i = 0; i < FOR_TIME; i++) {
    var test = {};
    Object.defineProperties(test, {
        a: {},
        ab: {},
        ac: {}
    })
}
console.timeEnd("props");

控制台结果如下:(执行3次)

1- prop: 9.251ms props: 17.034ms
2- prop: 10.050ms props: 22.443ms
3- prop: 11.013ms props: 17.086ms

使用的节点版本:v10.15.0

您可以将基准阅读为:"Oh, defineProperty is more than two times faster"。

或者您可以将其读作:"Even defineProperties only takes 20ms for 10.000 iterations, which means that it will rarely cause any problems at all, unless you are creating millions of instances in a loop that runs thousand of times."