This content originally appeared on DEV Community and was authored by Nick | React tinkerer ⚛️
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
};
P.S. Follow me on Twitter for more content like this!
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
This content originally appeared on DEV Community and was authored by Nick | React tinkerer ⚛️
Nick | React tinkerer ⚛️ | Sciencx (2022-02-06T09:33:00+00:00) Why does dynamically adding properties is slow in JavaScript?. Retrieved from https://www.scien.cx/2022/02/06/why-does-dynamically-adding-properties-is-slow-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.