Home >Web Front-end >JS Tutorial >Why is Modifying an Object\'s [[Prototype]] a Performance Killer in JavaScript?
Why is Modifying the Object's [[Prototype]] a Performance Killer?
The Mozilla Developer Network (MDN) strongly advises against altering an object's [[Prototype]], regardless of the method used. This warning stems from the significant performance penalties it incurs on modern JavaScript implementations.
While adding member functions to JavaScript classes through Function.prototype is recommended, both the following operations:
foo.__proto__.bar = bar; Foo.prototype.bar = bar;
are functionally equivalent and create a 'bar property on the Object.getPrototypeOf(foo)` object.
The issue lies not in creating the 'bar` property, but in assigning to the '__proto__ property itself:
fred.__proto__ = Object.prototype;
This operation breaks JavaScript engine optimizations for property access. By modifying an existing object's prototype chain, you effectively destroy any prior optimization efforts.
The V8 JavaScript engine, for instance, utilizes hidden classes to optimize property lookups. Changing the prototype chain invalidates these optimizations, forcing the engine to fall back to less efficient methods.
Experts in the field have expressed concerns about the performance implications of mutable prototypes:
The consensus is clear: mutating an object's [[Prototype]] is disruptive to performance optimizations and should be avoided. Instead, creating new objects with unique prototype chains using Object.create() is the preferred approach.
The above is the detailed content of Why is Modifying an Object\'s [[Prototype]] a Performance Killer in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!