Search code examples
javascriptnode.jsobjectinheritancev8

Using `__proto__` in object literals


If I am not mistaken, using Object.setPrototypeOf() and __proto__ to change object prototype is considered deprecated as a "very slow operation". Also, IIRC, this can degrade the performance of objects in V8.

Also, it is usually not recommended to add properties to an object after creation as it can degrade the performance of objects in V8 as well (if I understand correctly explanations like this).

So, if I need to create an object with defined prototype AND properties, I have two options:

  1. Object.create() with both prototype and property descriptors arguments set. This is rather cumbersome way.

  2. Object literal with __proto__ and properties.

So the questions: are these two options equal with regard to performance? Or is the second way is just syntactical sugar for the same postponed Object.setPrototypeOf() operation internally? Has the second way any drawbacks? Are these drawbacks implementation-dependent or common (spec-dependent?)?

UPD

See also discussions in cross-posts:

https://github.com/nodejs/help/issues/2901

https://twitter.com/vsemozhetbyt/status/1292057058213269504

A naive benchmark: https://github.com/nodejs/help/issues/2901#issuecomment-671027781


Solution

  • There aren't any drawbacks to using __proto__ in an object literal.

    From MDN:

    That syntax is standard and optimized for in implementations, and quite different from Object.prototype.__proto__.

    Object.prototype.__proto__ is deprecated but __proto__ in an object literal is not. __proto__ in an object literal was made standard in ES6 and was already supported by browsers such as Internet Explorer as far back as ES5. It was part of Annex B but it's being moved into the main spec.