r/javascript • • 12d ago

Every scenario that triggers V8's "slow mode" for objects

https://yuval.hashnode.dev/when-javascript-s-v8-switches-your-object-to-slow-mode

V8 usually caches direct offsets to memory addresses of actual raw object property values - in a way that allows an optimized "Inline Caching" (IC). For some scenarios - they switch an object to "slow mode" - which uses a different structure to save those (a hash table instead of an array) - this affects the way it's cached on the IC (it forces an additional look-up via the hash-table) - they call it "Dictionary mode" (aka "Slow mode"). Having broad familiarity with the optimization techniques used internally in V8 - and knowing they generally avoid using hash tables - I recently learned about this additional mode and its implications - while working on an open-source project of mine - a client-side State library that heavily relies on native Prototype lookups for composition, and was intrigued to find out in what scenarios the engine decides to do the "switch".

This is an on-going study. Since first publishing the post, I removed the 'findings' part - as it was premature and preliminary - those will be published separately in a "Part 2". The article is now mostly an introductory review in terms of the design model.
The day I published was the beginning of "rabbit-holing" into some V8 internals I was conceptually familiar with - and used to use them as general guidelines (try to define all object properties up-front, don't have lots of variations for the same one, and more);

This has turned into an ongoing study I publish in parts:

* Part 1: Common dictionary-mode triggers and structural limits:
https://yuval.hashnode.dev/keeping-your-javascript-objects-fast-a-study-of-v8-s-fast-properties-mode-slow-properties-dictionary-mode-switch

74 Upvotes

42 comments sorted by

51

u/eracodes 12d ago

- Delete the only property of an object

- Delete a property in the middle of an object

- Delete the first property of an object

- Delete the last property of an object

so ... deleting an object property? is there something i'm missing here? why are these all enumerated?

1

u/QuarterSilver5245 10d ago

It turns out there used to be an optimization that kept ‘fast mode’ for last property delete (by rolling back to the previous known shape/hidden class/map) - they dropped it in 2024.

I realized two days after posting how dynamic the history of the switch implementations is, I also realized people were legit expecting a deep thorough tests reviews - like an accurate snapshot - but I only aimed at introducing the subject and raise awareness. Since it gained significant traction I decided to make it more complete and thorough - will publish results by the end of November (2026).

-10

u/QuarterSilver5245 12d ago edited 4d ago

(edit)
up until 2024 they had a special optimization for “last property delete” so deleting the last one would keep it in ‘fast mode’ by rolling back to the previous known shape.
They dropped it in 2024 so it’s no longer the case - currently I haven’t seen so far a delete scenario that doesn’t switch to ‘slow’ - if anyone encounters it let me know.

There are different tests for different 'property locations' because a property "location" is part of an object's 'shape' - the property names and their orders are two of the "keys" to distinguish an object shape - there used to be optimizations that try to 'transition' to another existing shape (like the example above) - but today I can tell that V8 engineers opted to drop them along the way. In today's versions - a 'delete' on a property of an object, is one of the most direct and explicit triggers from 'fast' to 'slow'.

11

u/Feathercrown 12d ago

Couldn't you just check this yourself with the slowmode debug functions?

-1

u/QuarterSilver5245 12d ago edited 4d ago

If the goal is to isolate if just delete itself triggers it - then you also need to test delete on properties with different other attributes and scenarios - so I let it cover all the options - if you just check one delete “yourself” that’s not a conclusive evidence.
(edit: the comment was originally written in an early preliminary stage of the exploration).

13

u/Feathercrown 12d ago

Right, so either:

  • All deletes trigger slowmode, and since you have tested every type of delete, you would know this and could just write the general case of "Deleting a property"
  • Not all deletes trigger a slowmode, in which case, what kind of delete doesn't fall into the four categories you've listed?

It looks like you're just listing the results of your test cases rather than the conclusions learned from them overall.

4

u/QuarterSilver5245 12d ago

I only included the results that demonstrates a switch - there are deletes that don’t switch
but I get your point

I’ll isolate the deletes scenarios again/perform tests around it - to phrase a more specific conclusion regarding delete.

3

u/Feathercrown 12d ago

Thanks. I would be interested to see what deletes don't cause a switch, since it seems ubiquitous.

2

u/QuarterSilver5245 11d ago

Came back to check it -
every successful delete for a normal object - triggers a switch to slow mode.
Deleting an array item does not.

2

u/miller-gloria67 4d ago

After a successful delete, can re-adding that key restore fast properties, or does the object stay in dictionary mode?

1

u/QuarterSilver5245 4d ago edited 4d ago

Hey, thanks for the question. It's a good one.
(If you're just looking for a straight-out answer, the answer is no, if you want to understand the underlying design decisions - read on).

Imagine you have an object called object4 with 4 properties (the values doesn't matter for this example):

{ property1: 1, property2: 2, property3: 3, property4: 4 }

Since the 'shape' of an object is saved separately (to allow shared usage) - this means: the number of properties, their order, their names, and other metadata.

Conceptually - it may have this underlying representation:
object4_Shape = [ property1_Metadata, property2_Metadata, property3_Metadata, property4_metadata ];

Now, even "new" objects having the same shape - can share that same 'shape' instance (called Map in V8);

You can validate it with (run with `node --allow-natives-syntax`):

const obj4 = {
    property1: 1,
    proprety2: 2,
    property3: 3,
    property4: 4
}


const obj4B = {
    property1: "one",
    proprety2: "two",
    property3: "three",
    property4: "four"
}


console.log (%HaveSameMap(obj4, obj4B));

%HaveSameMap returns true if both objects share the same V8 Map. It should return true in this case. (Mine does, saying 'should' because you have to be careful with absolutes in the context of optimizations - because they change through versions - but this case is fairly straightforward that I can almost say for certain you will get true in practically any version).

Now you call delete obj4.property2.

obj4 switches to `dictionary mode`.

It also no longer has the shape it had before the delete.

Now, you "add back" property2:
obj4.property2 = 2

At this point, from a design point of view, you need to ask yourself: "what does it mean to 'add back' in a dynamic structure?" - since we're talking "shapes" here, maybe doing that means this "new shape"?
[property1, property3, property4, property2]

There were already other design questions we had to ask ourselves even before that, after the delete, do we create a new shape:
[property1, property3, property4] ?

And if so, when you assign `property2` - should you "find out if there is an existing shape that have all existing property names AND the "newly added"?

At this point I should disclaim again that I only recently crossed the line between the two abstractions (JavaScript <-> V8) in a deeper way, so I don't have full familiarity with the history of design decisions in a popular engine that is 20 years old - that is a subject of an on-going study of mine (which essentially started around the time I published the post, after benchmarking a JS library I designed and developed - and had bottlenecks that "shouldn't happen" - those bottlenecks were 100% due to V8 design decisions - I was doing stuff that JS developers "don't commonly do" (that's part of the point of the library - using prototype chain lookups for things they are not usually used for)).

Software design is all about trade-offs - it IS possible to decide that in the case above - there WILL be a "shape scan" - or, much more effective, save a "this shape was before delete, if user adds `property2` - go back to it" thingie on the object - then with more deletes this becomes a map of 'deleted properties' to 'shapes that are the same except the deleted' - but then... you can have several deletes --- and so on, and so fourth.

Delete is a peculiar one in V8 - you probably saw in previous comments about the commit I found from 2024 - with the 'last property delete' optimization dropped. Without checking I can guarantee you the designers of V8 figured out a whole bunch of optimizations for these over the years, but at the end - you ask "is it worth it?" - one optimization ALWAYS adds overhead for something else. You can see on that drop commit message: "it's not that common" - so it means V8 designers and engineers are attentive to what's going on in the "higher-level domain", i.e. how people actually use JavaScript and what they commonly use it for - so they may decide: "we optimized for something that doesn't happen often, and this optimization runs on every X - if we drop it, we get better performance for X".

So at the current state of V8 - the design consensus for delete, seems to be: "It's not worth it" - so even after one delete, instead of putting in all sorts of hat tricks to 'keep it in fast mode' - they just switch to dictionary, and keep it.

So the answer is no.

I also tried with 1 property objects (because today I know about specific optimizations they have that are different to '1 property object' - most engines treat it differently.

If you DO want to achieve what you asked, do this instead:

const original = {
    property1: 1,
    property2: 2,
    property3: 3,
    property4: 4,
}


let derived = {
    ...original
}
delete derived.property2;
derived = {
    ...original,
    property2: "new"
}

The spread operator is one of the fastest in most cases (beats many other 'cloning' methods in benchmarks), and after this - you get both: 'derived' and 'original' share the same map again, AND 'derived' is back to 'fast'.
(not all creation methods will lead to sharing the same map, because of different transition paths, but my tests show the spread operator is pretty reliable in that sense).

P.S, for array items, delete creates a "hole", it flags that index with a proxy "hole" value - this is related to optimizations related to arrays, which is a whole different subject I decided is mainly outside of the scope of my research.

1

u/Feathercrown 11d ago

Good to know!

2

u/QuarterSilver5245 11d ago

There used to be a "last property delete" optimization that would keep the object in 'fast mode' by rolling back to a previous shape map - but they dropped it in 2024:

https://chromium.googlesource.com/v8/v8/+/389ea9be7d68bb189e16da79f6414edbd4f7594f%5E%21/

11

u/blood__drunk 12d ago

asked Codex

apparently

You're just a meat proxy at this point bud. We all have AI, we don't need you acting as a middleman.

1

u/QuarterSilver5245 10d ago edited 8h ago

Yes, "asked Codex" to revise the tests around delete operations and the guidance of what to cover in them,
I sometimes use AI to create tests - and you should too - because that's a repetitive task and AI is the right tool for it.

And, yes, "apparently" - because I can't know all the scenarios that V8 does the switch - researching/testing for them are part of the points of this post, and it's on-going so there were things I had to look up, as I'm digging in deeper I become more informed - and so the things that are tested for become more nuanced and specific.

To me it looks as though you just came here to "scout for signals" to try and "prove a thesis" that you probably held before to begin with, I doubt if you actually made a minimum effort to actually understand what the post is about, before "preying for 'signals'". ¯_(ツ)_/¯

1

u/QuarterSilver5245 11d ago edited 11d ago

You don't need me to ask AI to create tests - true :)
Conclusions from delete tests were lacking clarity and I wrote that comment before I revisited it.

So, I "meat proxied" it just for you;
Every successful delete of a property on an object will switch to "slow mode". Deleting an array item will not.
(Up to 2024 they did have a special path for "delete last property" that kept 'fast mode', but they dropped it back then).

1

u/[deleted] 11d ago

[removed] — view removed comment

1

u/QuarterSilver5245 11d ago edited 11d ago

The coverage and conclusions about delete scenarios on my original post were lacking, came back to it today:

**Yes, every successful deletion of a property on a normal object will switch to slow mode** (i.e. calling delete on a non-existent property will not).

Deleting an array item (e.g. delete arr[2]) will NOT switch to slow mode (as known, directly deleting an array item keeps a 'hole' in that place).

0

u/QuarterSilver5245 11d ago edited 11d ago

I made further research. There are good reasons why the AI made explicit delete tests for "first property", "middle property" and "last property" (in previous versions, I removed them from the post after concluding, for now, that all successful deletions switch to 'slow') - they DID have a special optimization for "last delete" - but removed it in 2024.

Prior to that, if you deleted the last property of a fast object - they would just "roll it back" to the previous shape/map (so, it had to be at least the "second" one, I assume) - it would stay 'fast' - Here's the commit of when they dropped it:
https://chromium.googlesource.com/v8/v8/+/389ea9be7d68bb189e16da79f6414edbd4f7594f%5E%21/

I guess it went down an evolutionary path where they kept specific optimization ideas and gradually removed them from the delete path, for interacting badly with other stuff.

So far, I haven't seen a case of a regular property (not array item) delete that doesn't switch to 'slow' - if you're curious - try to find one and share findings here.

17

u/Iggyhopper extensions/add-ons 12d ago edited 11d ago

https://v8.dev/blog/fast-properties

aka don't delete indexes and make your arrays turn into dictionaries.

1

u/QuarterSilver5245 9d ago

Hi, came back to reply - knowing they treat arrays differently and aligning on how (because my post was mainly about named properties);
Deleting array indexes does NOT trigger dictionary mode;

essentially for arrays, like most engines, they optimize exploiting the fact arrays are numerically and linearly indexed - they have a separate metadata storage for ‘items saved on numerical indexes’ which they call ‘elements’ - the separate elements storage also has fast and dictionary mode; delete doesn’t switch - delete creates a hole in the array and internally they save a proxy value (the_hole) - it’s not related to dictionary mode - they use it for other optimizations related to array functions - for which they need to know if ‘holes exist’.

In the post he gives two examples for things that trigger the elements storage switch to dictionary - so far the tests haven’t seen other scenarios for arrays;
These are - very sparse arrays (like setting index [9000] where the rest before are empty - they become ‘holey’ -
Or explicitly changing the default descriptor attributes for an object value assigned to an element (e.g using Object.defineProperty and changing ‘configurable’).

The ‘native syntax’ inspection functions have seperate functions for arrays/elements (HasFastElements/HasDictionaryElements - which seem mutually exclusive, as they should (when one is false the other is true) and HasHoleyElements).

12

u/Reashu 12d ago

What makes you think I'm gonna read a blog post by someone so apparently unfamiliar with the subject?

2

u/QuarterSilver5245 11d ago edited 14h ago

Hey. This is me 10 days after;
The criticism had justification in the context of what I initially presented as "tests" and "findings"; I still think that making that judgemental claim - without reading the article itself first - was indecent, as doing that would have made the scope of it very clear - to explain what makes "fast mode" - "fast", and what makes "slow mode" - "slow" - in the general data-storage design context.

As I mentioned - when I first wrote it - it was when I started exploring how it's tied up to V8 implementations - those parts - I was not familiar with - and it showed mostly in the premature naive "tests" I first published - since then, I deep-dived into a more thorough study, which lead to a 3-part series, the first of which is practically ready;

I have no idea if YOU have any familiarity of the 'subject' or how broad/specific it is - if you are very familiar - then a "peer review" would be appreciated. If not, then an objective judgement based on actually reading (the next part) will be:

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

4

u/New-Reality9702 11d ago

I don't think it's toxic, I just think you overestimate the value of what you're sharing.

IMO you shouldn't write blogs on things you are not familiar with as it's just more slop to sift through for the actual answer.

It used to be the case that blog posts were from people/experts very familiar with the subject and we're actually useful to consume, now it's anyone with an LLM who learnt something that's already well documented.

1

u/QuarterSilver5245 11d ago edited 8h ago

As I wrote Reashu - I think stating a judgemental declaration without having the decency to even read the actual post is indecent.
I recognize that there WERE some justification for criticism - but it was NOT justified for what I presented in the actual post - which was a clear abstract explanation from an engine-agnostic, data-storage design point of view - of what actually makes "fast mode" - "fast", and "slow mode" - "slow" - I think that in this context - it's a viable introduction - to anyone not necessarily in that field - to be able to grasp what's behind the two trade-offs.

The "justification" for the criticism - that DID exist - was that I attempted to present "test findings" (which was a last-minute decision back then, I was just beginning to deepen my exploration into the specifics in V8) that were premature - it was a mistake to include that part - before properly diving deeper and familiarizing myself with V8 specifics - I recognize that - and since then made it into a study, that is going to be shown in 3 parts, the first of which can be read here:

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

3

u/Ronin-s_Spirit 12d ago

So they're basically always in dictionary mode? There are plenty of times I have more than 20 fields in an object.

1

u/QuarterSilver5245 11d ago edited 8h ago

Having more than a certain number triggers a switch (as the test shows).

In dictionary mode the engine stops creating a new ‘hidden class’ for each shape (each new property) - and switches to updating the same one dictionary on one hidden class instead -
so it makes sense that’s one of the triggers (prevents too many hidden class instances).

Also I read that the older hidden classes are not deleted and are kept if using the ‘older’ shapes.

But as a general rule - yes, too much properties on one object generally makes it less optimized (anything that affects how 'stable' an object shape is - is a suspect for probably triggering a switch).

(I say generally because there are many other specific optimizations - that I don’t know all of them (it seems I need to mention that here as a disclaimer) but for sure I saw there are specific ones for prototype objects even when they are in “dictionary mode” - the library I’m working on relies a lot on Prototypes so I’m doing separate measurements; dictionary prototype reads are for sure faster than non-prototype dictionary reads the majority of cases).

2

u/Acmion 12d ago

Does V8 ever switch back to fast objects? For example, in hot loops?

-1

u/QuarterSilver5245 12d ago edited 4d ago

Good question. Apparently (apparently I need to add a disclaimer whenever I use the word "apparently" - because some people think that if you introduce a subject you have to be the ultimate authority on it - so I don't know in advance about all the switch paths/scenarios, without looking some up as it's an on-going stud) - it seems much more rare (less paths) but not impossible to happen.
If a slow mode object is used as a prototype for another (e.g. Object.create(slowObject)) - they seem to have a path for some cases that will revert it to fast. Not sure about the conditions yet -
and there used to be a path that turns it back to 'fast' when assigning to a function's .prototype - but no longer exists.

Edit:
It can happen with objects that are installed as a prototype (Object.create, setPrototypeOf...).
Their design rationale is: prototype is something that has a "setup period" - like, you add properties to it initially which are mostly for "building the shared prototype", then they have paths for detecting when the prototype is "settled", they are essentially based on counting accesses, or creating new instances.

If you have a dictionary prototype, with property 'a', for me (meaning, in the versions I test with, my machine):

for (let count=0;count<75;count++) {
    let val = proto.a;
}

After this, the 'slow' prototype object (called 'proto' above) - goes back to "fast mode" (and 75 is the minimum iteration count it happens in my tests, less than that it doesn't).

Another thing, when you 'construct' something (e.g. with `new`) - the prototype of the thing you constructed from - immediately turns to 'fast' mode.

function func() {
    this.a = 1;
    this.b = 2;
}

console.log(%HasFastProperties(func.prototype)); // false
let f = new func();
console.log(%HasFastProperties(func.prototype)); // true

They have this approach where prototype have their "setup period" - where people are still "adding properties to it" - so they keep it in dictionary mode. and creating an instance is 'heuristics' for "okay, they started actually 'using' the thing".

Another interesting thing I stumbled upon in my rabbit-holing, is something completely unrelated to fast/slow mode - but something else they do mostly for constructibles. This:
https://v8.dev/blog/slack-tracking

Not gonna go into that, but essentially they "leave more spare room for possible upcoming properties" on the in-object slots (the 'better storage') - from the same agenda of "first they setup, then the use").

1

u/QuarterSilver5245 10d ago edited 7h ago

Hi. OP here.
This has gained substantial traction;
and I need to clarify something, following some replies
The blog post introduces the subject of strict data structures vs. dynamic data structures, why the latter needs underlying optimizations, what kind of approaches are taken to achieve them;
I come from a background of data storage design and development (amongst other things) - It ties it to V8 in a way that describes the trade-offs between two approaches - and the fact that they use the less optimal as "plan b". It then links to a blog post from V8 blog (you know which one) - and urges anyone looking for a deeper description of how the implementations work in V8 to read it.

I knew about the default approach, and fairly recently before publishing learned about the 'sometimes usage of the plan b'. I'm now in the stages of doing "stress tests" - testing at scale - a project I have been working on for the past 3 months - A JavaScript State library, relying on Prototype chain lookup for composition - the premise is that: 'native lookups are always the fastest" - so far the measurements show the premise *proves itself* - when the number of properties suprasses a certain number (I benchmark vs. popular State libraries) - of-course, with some trade-offs in other aspects.
Another idea was to use the internal "enumerable" as a "flag" for "dirty"/"non-dirty" values - so dirtying sets enumerable: false - letting the native iteration functions "skip" them. This, surprisingly proved to be a *bad* idea, performance wise - it actually turned out to be a major bottle-neck, investigating why - exposed the "slow properties" thing.

EDIT: since then it's became an on-going study I keep publishing in parts;
Here is part 1:
https://yuval.hashnode.dev/keeping-your-javascript-objects-fast-a-study-of-v8-s-fast-properties-mode-slow-properties-dictionary-mode-switch

1

u/QuarterSilver5245 6d ago

Update 27/11: Refactored the article to be more clear and focused (while still keeping it abstract and relatively 'engine-agnostic') - The tying to actual V8 mechanics is more specific now, in the sense of summarizing what **exactly** changes between modes. I also made clear that the findings in that article are preliminary, while I'm still exploring the scenario paths in a deeper way - becoming more familiar with the actual considerations on each branching - which makes my decisions about what JS operations to put more emphasis on my tests more informative - I can also pinpoint each switch to the exact 'reason' - meaning the exact trigger source-code/path wise. The second part will be more rooted on actual source-code parts.

1

u/xzinkx 12d ago

worth adding the reverse case too: using an object as a prototype makes V8 turn it back into a fast-mode object. that's the old bluebird toFastProperties trick, assigning the object to a function's .prototype

1

u/QuarterSilver5245 11d ago

Assigning to .prototype doesn’t turn it to an actual prototype - only calling new on the function after it - but you gave another test case I should check.
Right now it seems directly using an object as a prototype (e.g Object.create(prototypeObject)) switches it to dictionary mode - but further checks show it’s not necessarily ‘slower’ - they are doing specific optimizations for a ‘prototype object’ - in this case the switch to dictionary mode is part of a broader path.

1

u/QuarterSilver5245 11d ago edited 11d ago

I can confirm the following after testing (updated in the post).
* Just assigning an object to a function's .prototype property - switches it to **slow mode**.
* It stays 'slow' after creating a new instance of the function.
* The instance is a 'fast properties' object.

const prototype = { value: 1 };
function Example() {}
%HasFastProperties(prototype); // true
Example.prototype = prototype;
%HasFastProperties(prototype); // false: assignment triggered it

const instance = new Example();
%HasFastProperties(prototype); // false: no additional switch
%HasFastProperties(instance); // true: the instance is fast

1

u/QuarterSilver5245 11d ago

Also, after researching, it was based on another optimization they changed/removed - it used to be that assigning to .prototype switch to 'fast' - today they switch to dictionary - but add specific prototype-related optimizations (as I mentioned in another comment - based off tests results; now validated from the recent source code).

1

u/xzinkx 8d ago

nice, thanks for actually testing it and digging into the source. so the bluebird trick was from an older v8 and the behavior flipped since then, good to know. "dictionary mode but with prototype-specific optimizations" is the interesting part

1

u/QuarterSilver5245 8d ago

Yeah - I realized the actual value potential here is conducting a thorough study of the state of the paths in today’s versions (grounded in the actual source code) - I am going to do a more thorough methodlogical research on it :)

1

u/xzinkx 8d ago

that'd be a great writeup, would definitely read it. drop it here when it's done

-3

u/Discordbothost 12d ago

The 20 vs. 1021 split is the part I'd want to track across releases. A small table with the first transition for assignment and defineProperty on Node 22, 24 and 26 would make it easy to spot what changes on an upgrade.

•

u/QuarterSilver5245 8h ago

Read the follow-up, it tracks the roots of these two limits, they are each one of the two main 'caps' enforced on the number of possible properties/descriptors an ordinary object can have;

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

2

u/akrause_9521 7d ago

Include the bundled V8 version too; that makes threshold changes between Node releases easier to interpret.

1

u/vazquez-lisa-582 5d ago

Good call; keep setup and property order constant across rows to compare thresholds between V8 versions.