Why is dynamically adding properties slow in JavaScript?

Nick - Feb 6 '22 - - Dev Community

JS gives an ability to add properties to the object after it was created.
It gives a lot of freedom but has a performance cost at the same time.

👉 JavaScript’s object model

The ECMAScript specification defines all objects as dictionaries, with string keys mapping to property attributes

Property access is the most common operation in real-world programs => "Value" needs to be accessed fast, so shapes come into play.

JavaScript’s object model

👉 Shapes

Multiple objects have the same shape if their properties are the same.
If it's the case, the JS engine stores their Shape separately, and then JSObjects point to it.

Shapes store the "Offset" of the value inside JSObject, instead of the "Value" itself.

Shapes

👉 Transition chains

When you dynamically add properties to the object, its Shape form a so-called transition chain.
Next time you access a property of the object, the JS engine needs to traverse its transition chain.

At scale, performance suffers in this case.

Transition chains

👉 How to optimize it like a top-performer?

vNode properties are accessed on every render in Preact, so this operation needs to be extremely fast.

To achieve it, Preact developers add all properties in advance and assign undefined/null to yet unknown.

const vnode = {
  type,
  props,
  key,
  ref,
  _children: null,
  _parent: null,
  _depth: 0,
  _dom: null,
  _nextDom: undefined,
  _component: null,
  _hydrating: null,
  constructor: undefined,
  _original: original == null ? ++vnodeId : original
};
Enter fullscreen mode Exit fullscreen mode

P.S. Follow me on Twitter for more content like this!

. . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player