Are the keys of JavaScript Objects stored in memory?

Viewed 542

I want to know if it uses more memory to store an Array of Objects having the same keys, than just storing an Array of Arrays containing the values.

const arrayOfObjects = [
    {key1: "val1",      key2: "val2",       key3: "val4",       key4: "val5"},
    {key1: "value1",    key2: "value2",     key3: "value4",     key4: "value5"},
    {key1: "value-1",   key2: "value-2",    key3: "value-4",    key4: "value-5"}
]
const arrayOfArrays = [
    ["val1",    "val2",     "val3",     "val4"],
    ["value1",  "value2",   "value3",   "value4"],
    ["value-1", "value-2",  "value-3",  "value-4"]
]

Will arrayOfObjects take much more memory than arrayOfArrays? More precisely, are the keys also stored in memory? Also, I often use JS Objects to make hash tables, to accelerate algorithms, but what are the limits of doing that ? Thank you for your help.

2 Answers

JavaScript itself doesn't specify memory layout of objects, but all the common implementations use something similar to the object shapes of the V8 engine. Since all your objects have the same shape, their property names will be stored only once and shared by all objects in your array, no matter how many objects there are. The overhead compared to arrays, if any, is not worth considering in your algorithm/data structure designs.

I often use JS Objects to make hash tables, to accelerate algorithms, but what are the limits of doing that?

Engines will use a different object representation if you add too many properties, dynamically, or even delete them. However, for a hash table you should use a Map in modern javascript, which is optimised for this use case from the ground up and much more efficient than an object.

Unlike structure member names in a language like C, which are resolved at compile time, JavaScript property names are dynamic and can be changed at run time. So they have to be stored in the memory of the objects. JavaScript objects are generally implemented as hash tables, with the property names as string keys in the table.

However, if you use the same property names in multiple objects, there will usually be just one copy of that string, which is shared by all of them. See Do common JavaScript implementations use string interning?. So the strings are stored in memory, but not duplicated for each object.

The code that implements objects is highly optimized, since your uses of them are typical and need high performance.

Related