Search code examples
javascriptecmascript-5defineproperty

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


I am looking for a main differences between those two methods.

Some sites mentioned readability concerns, but my concern is mainly performance related. Seems like defineProperty() is faster, but i couldn't find out why.

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");

Here is the result of the console results : ( executed 3 times )

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

Node version used : v10.15.0


Solution

  • You could read the benchmark as: "Oh, defineProperty is more than two times faster".

    Or you could read it as: "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."