Home  >  Article  >  Web Front-end  >  Why is Modifying an Object\'s [[Prototype]] a Performance Killer in JavaScript?

Why is Modifying an Object\'s [[Prototype]] a Performance Killer in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 20:09:03474browse

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:

  • Brendan Eich: "Writable proto is a giant pain to implement... and it creates all sorts of type-confusion hazards."
  • Brian Hackett: "Allowing scripts to mutate the prototype... makes it harder to reason about the behavior of a script and makes VM, JIT, and analysis implementation more complex and buggier."
  • Jeff Walden: "Prototype mutation after creation, with its erratic performance destabilization, and the impact upon proxies and [[SetInheritance]]"

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn