r/javascript • • 2h ago

Keeping Your JavaScript Objects FAST: a Study Of V8's "Fast Properties Mode" <-> "Slow Properties/Dictionary Mode" Switch

https://yuval.hashnode.dev/keeping-your-javascript-objects-fast-a-study-of-v8-s-fast-properties-mode-slow-properties-dictionary-mode-switch

This is a follow-up to my study of JavaScript objects transitioning from “Fast Mode” to “Slow Mode” in V8;
It explores 4 different JavaScript scenarios, that will trigger a JavaScript object to be switched from the normal "fast properties" mode, to "Dictionary" (a.k.a "slow") mode. The fourth one is a substantial finding that was not shown in previous prelimenary results.

The goal is to find deterministic or "mostly deterministic" scenarios that trigger a switch from fast mode to slow mode - a "mostly deterministic" scenario is a kind of operation (usually an object mutation, creation, property addition or property redefiniton) - that, except uncommon exceptions - given a "fast mode" object - will trigger a switch to "slow mode", under the same conditions.

The background story is that, while benchmarking a client-side state-management library I've been developing, I encountered an unexpected performance bottleneck: changing the enumerable attribute of certain properties affected subsequent property-access performance. Investigating this has led me to take a step - crossing between the abstraction boundaries - from the JavaScript realm, to its underlying runtime engine, V8, and the specifics of the implementations of "Fast Properties" and "Dictionary/Slow properties".

I initially wrote an article explaining why "Fast Mode" is "fast" and why "Slow Mode" is "slow", from a data-storage design perspective, tying it loosely to V8's implementation (which I was not deeply familiar with at that time). That article now serves as an introduction to this study.

This series documents that investigation through reproducible experiments and references to V8's source code. The goal of the study is to identify deterministic or "mostly deterministic" scenarios that trigger a switch from “fast” to “slow” - a "mostly deterministic" scenario is an operation - typically an object mutation, or creation, that triggers a switch under specific, predictable conditions. Paths that are very narrow or very circumstantial - are outside the scope - and I intentionally do not pursue them.
Note, that what's known in V8 as "Elements" (a separate storage of array-indexed properties) - is outside the scope of this study as well. (Fun fact: Elements are not exclusive to “actual arrays”, ordinary objects also come with a built-in empty, but ready, Elements storage, which is used if you assign properties to numerical-indexes. It's what enables Array.from to work seamlessly with an object with number-keys and a length property).

I have decided to split this into several parts:

  • General deterministic operations; things that trigger a switch - with few or no additional conditions. This is this part.
  • Maps-transition-based triggers; Switch scenarios occurring as part of the Map transitions check “crossroads”: Initializing an object, adding properties, and changing aspects of existing properties - can all bring an object to this crossroads - where V8 tries to figure out whether to keep its current associated Map/Shape, transition to another existing one, create a new one, OR, a fourth option, switch the object (if it’s still in Fast mode) - into “Dictionary/Slow mode” - that fourth option is what the study investigates.
  • Operations on Prototype objects. Objects defined as a Prototype goes through different paths/branches/conditions - so they deserve their own separate part.

The motivation and perspective is that of a veteran JavaScript engineer investigating the implementation details of an underlying abstraction after encountering limitations originating from its design decisions, while not being a member of the developers/maintainers of V8 - the series documents an active investigation - discoveries, experiments and limitations.

I consider this information important, especially since not all scenarios that switch are intuitively apparent (you will see that especially in part 2).

My previous post revealed that the community sees value in actual “Do’s and Don’ts” on this matter - which encouraged me to conduct a more thorough, systematic study, grounded on resources such as V8 source-code, both current and historical, and specific, dedicated, reproducible tests and code examples;

The linked article elaborates on each finding, with source-code references and reproducible examples. Here, I'll provide a condensed version;

This is an ongoing study; I encourage discussions around the scenarios presented here, if you mention related scenarios outside of the scope here and have interesting findings - I’d be happy to see them contributed. Please maintain respectful communication; Constructive remarks are welcomed;

---

This part has 4 findings:

1. Creating an object with null Prototype; This might be the most explicit, deterministic way to have a dictionary-mode object, from JavaScript syntax. V8 source code actually has specific conditions for this (a literal “is_null_prototype” const). In practicality - this is essentially a “JavaScript API for intentionally creating a Dictionary object”. Also, there is no “switch” - the object is initialized as “dictionary mode” from the get-go. It works with Object.create(null), as well as with { __proto__: null }, but, NOT when using Object.setPrototypeOf(object, null).

2. Having too many properties; Although this is triggered as part of the Maps transitions flow - I decided it’s generic enough to include it in the first part (and not the second); There are two limits:

  • A “soft-limit”: this is the Max of a V8 configuration flag vs. the in-object property storage capacity, compared against the number of external property fields (named properties storages for 'fast properties' can be a "in-object" storage, or an external storage (the first is slightly faster as it skips an additional lookup step)); I have found this limit is applied when you assign properties using “dynamic keys” (e.g. object[key] = “value”). Don’t count this number as an absolute - but on my test environment - adding dynamic keys until it switches consistently occur on the 21st addition.
  • A “hard limit”: this is a hard coded cap on the maximum number of total fast property descriptors an object can have. The limit is written as: (1 << kDescriptorIndexBitCount) - 4; kDescriptorIndexBitCount has been hard-coded to 10, with no change since 2013; The shift-left is equivalent to 2 to the power of 10, === 1024. So minus 4 is 1020; Tests of adding direct named properties to an object until a switch is triggered - show a switch on the 1021st property, consistently.

3. Deleting a configurable named property; You might of seen this come up on the first post; There aren’t a lot of optimization attempts to “preserve fast mode” after delete (the article explores reasons why); There was a now-obsolete optimization that sustained fast mode when deleting the last named property - but currently - for NON-PROTOTYPE objects, this seems like a mostly deterministic switch trigger.

4. Defining a literal getter/setter on an object; I think this is a substantial, important finding; Defining a “literal getter” or “literal setter” on an object - snaps it to dictionary mode.
By “literal”, I mean, this syntax:

const object = { 
   get someValue() { return 10; } 
}

As opposed to passing a descriptor to Object.defineProperty(/ies), with get() {...} and/or set(value) {...} - the de-facto way of defining an “accessor property” (the other kind, being a “data property” - where you put a direct { value: ... } in the descriptor. That distinction is going to be very relevant in part 2 - as most scenarios in that part are mutations related to accessor properties).

This syntax, also triggers a switch:

const object = { 
   get [“someValue”]() { return 10; } 
} 

This, though, doesn’t:

const key = "someValue";
const object = {
   get [key]() { return 10; }
}

An important thing to mention is, that both syntax forms (literal vs. Object.defineProperty) - leads to the creation of an accessor property (if you define both a setter and a getter for the same name in the literal variation - it's still the same one accessor property) - but, exploring the source code paths, reveals different initial execution points (they converge later-on) - the literal syntax path initially goes through a "Runtime Function" (one form of JS-to-C++ bindings they use within V8 to implement JavaScript functionality in the "C++ level". It's one of the "older" binding mechanisms, newer have been added - it's still in use - but it can hint about a specific's path "age"), the Object.defineProperty syntax initially follows a path that goes through methods that correlates to abstract operations mentioned in the ECMAScript specs under the same names;

My hypothesis - is, that specs came later (I mean, some specifics regarding "define property" was added in later specs' versions) - and defineProperty was adjusted to align, while the literal syntax remained in the older path.

Stay tuned for the next part, which is called:
"Accessor Properties - and why you shouldn't be messing with them - too much".

1 Upvotes

0 comments sorted by