Search code examples
javascriptobjectv8

In JavaScript how do objects keep track of key/value insertion order?


Have a look here:

The de facto standard is to match insertion order

How is this achieved internally in the engine? (let's say v8 for simplicity)


Solution

  • The Mozilla folks did a great blog post on the Anatomy of a JavaScript Object. In short (and in case the link ever stops working), Firefox uses three data structures to track an object's properties.

    The first is the object's array of values. Anything you store in a property gets added to this array. Since it's an array, the JavaScript engine isn't allocating small bits of memory off the heap every time an element is added. It's faster this way & doesn't fragment RAM.

    The second is the object's "object map", which maps keys to JSScopeProperty objects. Because the map is a linked list under the hood, with the most recently added property at the head, the JavaScript engine can iterate through the list from tail to head and get all the properties in the order they were inserted.

    JSScopeProperty objects remember the property value's index in the array, as well as other metadata related to the property. That's how JavaScript links property names to their values.

    Having two separate data structures like this saves on dynamic memory allocation (which kills performance) and gives the JavaScript engine opportunities to save memory by pointing multiple JSScopeProperty instances to the same value in memory or even re-using the entire object map if two objects have identical properties.