5

Why does dynamically adding properties is slow in JavaScript?

 2 years ago
source link: https://dev.to/fromaline/why-does-dynamically-adding-properties-is-slow-in-javascript-4hm8
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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.

👉 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.

👉 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.

👉 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!

unknown tweet media content
Nick | React tinkerer ⚛️ profile image
Nick | React tinkerer ⚛️
twitter logo
You can render React App without a wrapper!

Did you know you can render <App /> without id="root" wrapper?

Let me show you 👇
13:45 PM - 28 Jan 2022

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK