Question

I am trying to implement a straightforward associative array (no duplicates) with string keys and instances of my own "classes" as values in JavaScript. I am happy with expected O(1) behaviour of a hash set or the O(log n) access time of a set implemented as a balanced tree.

I am drawn to the simple use of an object to which I dynamically add new properties but I am on Node.js and have come across the V8 optimisation of hidden classes (see description of V8 hidden classes here).

If I do use properties on an object, will the V8 runtime notice the sheer number of properties and their transience and stop trying to JIT hidden classes behind the scenes?

I just cloned the V8 code, so pointers into it would be welcome alongside the top-line answer to my question.

Thanks for your help.

Follow-up 1

Thanks @vyacheslav-egorov, I see the guard code below in JSObject::AddFastProperty at your link. Without digging through more code it seems like a lot of overhead on every new property insertion. I think I see something like a per-object mode which causes JSObject::AddFastProperty to never be called any more. So JSObject::AddProperty calls straight through to JSObject::AddSlowProperty without much fuss. Do I need to do anything to push an object into that mode, or will the V8 runtime switch it over reliably using its own metrics?

if ((!name->IsSymbol() && !IsIdentifier(isolate->unicode_cache(), name)
     && name != isolate->heap()->hidden_string()) ||
    (map()->unused_property_fields() == 0 &&
     TooManyFastProperties(properties()->length(), store_mode))) {
Was it helpful?

Solution

Yes, V8 switches object properties to a dictionary representation when it notices that object has too many properties.

How many is "too many" depends on several factors (how was the object created, how many properties it had initially, how are properties added to the object). For example if an object was created as an empty object literal "too many" would be around 30 properties.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top