What is the impact of setPrototypeOf performance on a new object?

MDN values ​​that use .setPrototypeOf() will .setPrototypeOf() affect the future performance of your code.

I also read several Questions about why modifying the [[Prototype]] object reduces performance. But none of the answers explained what was happening in the background. So I wonder if this also applies to new objects.

In particular, I really like to do things like this:

 var MyPrototype = { method1 : function(){...}, method2 : function(){...}, ... }; var newObject = Object.setPrototypeOf({ property : 1, property2 : 'text' }, MyPrototype); 

Unfortunately, you cannot do this with Object.create , since it does not accept a literal of a simple object.

Is my use of setPrototypeOf also a performance degradation of the executable JS engine?

+6
source share
2 answers

If you are afraid (apparently you should ...) of the performance impact on the use of Object.setPrototypeOf() , but want the syntax to create an object similar to how your code is structured, try the following:

 var MyPrototype = { method1 : function(){...}, method2 : function(){...}, ... }; var newObject = Object.assign(Object.create(MyPrototype), { property : 1, property2 : 'text' }); 
+5
source

Another option is to combine the object literal with a shallow copy of myPrototype , although this may not be your desire.

 var MyPrototype = { method1 : function(){}, method2 : function(){} }; var newObject = Object.assign({ property : 1, property2 : 'text' }, MyPrototype); 
0
source

All Articles