4 ms·
> Now, you would assume that for both p1 and p2 the same hidden classes and transitions would be used. Well, not really. For “p1”, first the property “a” will b
by kevmo314 9y ago
> Now, you would assume that for both p1 and p2 the same hidden classes and transitions would be used. Well, not really. For “p1”, first the property “a” will be added and then the property “b”. For “p2”, however, first “b” is being assigned, followed by “a”. Thus, “p1” and “p2” end up with different hidden classes as a result of the different transition paths. In such cases, it’s much better to initialize dynamic properties in the same order so that the hidden classes can be reused.
Does that mean an object with n properties takes up O(n^2) memory for the class definitions or O(n!) if the classes do not guarantee a property initialization order?
- ridiculous_fish 9y agoAn object with N properties will typically require N hidden classes, forming a chain back to the empty class. However most hidden classes only require a constant amount of memory, so this is O(N) allocation size. If you initialize the same properties but in a different order, you'll get a new list of N hidden classes. In the worst case you could indeed have O(N!) hidden classes, if you construct with every possible initialization order.
- inglor 9y agoAre you sure of that? If I recall correctly from the source an object with N properties typically requires 1 hidden class (for that object). In order for it to require 8 it needs to add properties very dynamically. Am I remembering this wrong?
- ridiculous_fish 9y agoYou can see the description of how hidden classes work on the v8 wiki [1]. The short explanation is that the way v8 finds a hidden class is by following a chain of transitions starting at the empty class. Intermediate classes have to be kept around to retain the transitions. That is, in code like: function Point(x, y) { this.x = x; this.y = y; } v8 retains the hidden class for {x}, so it can find the hidden class for {x, y}. [1] https://github.com/v8/v8/wiki/Design%20Elements#fast-property-access https://github.com/v8/v8/wiki/Design%20Elements#fast-propert...