2

I have been hearing quite a lot that Object.setPrototypeOf() in JavaScript is not a good thing to do. It reduces optimizations and lowers down the performance of an application.

Specifically, it reduces some inline caches and fast prototype property lookups made for a given object.

Now, I have one question in my mind that doesn't seem to have been answered anywhere online. That is:

If Object.setPrototypeOf() removes inline caches and wastes other optimizations, then this would only be applicable, and rigorously true, when it's called multiple times while an application is running. For e.g. if I have an object o and I, let's say, change its [[Prototype]] on click of a button, then this would be the bad thing.

However, I don't see any issue whatsoever, in doing the following thing:

function Parent() {
    this.a = 1;
}

Parent.prototype.helloParent = function() {
    console.log('Parent.');
}

function Child() {
    this.b = 2;
}

Child.prototype.helloChild = function() {
    console.log('Child.');
}

Object.setPrototypeOf(Child.prototype, Parent.prototype);

Two constructor functions Child() and Parent() are created, and then Parent.prototype is set as the prototype of Child.prototype. This prototype mutation via Object.setPrototypeOf() is done immediately before any other code is run, so perhaps once the first property lookups on Child instances are performed, the JS engine could optimize their property accesses.

I couldn't understand exactly what might be the performance issue with this code specifically, assuming that Object.setPrototypeOf() is called in the application only in this way.

coderboy
  • 1,710
  • 1
  • 6
  • 16
  • 2
    _"I have been hearing quite a lot that Object.setPrototypeOf() in JavaScript is not a good thing to do. It reduces optimizations and lowers down the performance of an application."_ - If you add such assumptions/statements in your question then please also add an example (+ a link to the source) for those. – Andreas Sep 30 '21 at 07:04
  • 1
    [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf) has a warning box as the first ting in their docs. They suggest creating a new object instead of changing the prototype. – Nils Kähler Sep 30 '21 at 07:08
  • 1
    Yes, I know about that. But that doesn't answer my question. – coderboy Sep 30 '21 at 07:43

0 Answers0