1

I was wondering if an object e.g.

const numbers = {
      a: 1,
      b: 2,
      c: 3
};

is stored as a group in memory so that the variable 'numbers' refers to the entire object in one place, or if each of it's individual keys are stored in different places as individual items that are all connected by many separate pointers somehow? Thanks.

j obe
  • 1,759
  • 4
  • 15
  • 23
  • Sometimes depending on your level of knowledge, reading detailed specs doesn't always help with an easy to understand answer. – j obe Jan 10 '21 at 17:04

1 Answers1

4

(V8 developer here.)

The short answer is: yes, at least in such simple cases that's a reasonable assumption.

The longer answer is that it's complicated, and also totally an engine-internal detail: different JS engines, and different versions of them, may well choose to represent (large, complicated) objects differently internally. For example, V8 stores "named" and "indexed" object properties separately, e.g. if you had numbers = {a: 111, b: 222, 0: 42, 1: 43}, then the 42 and 43 would be stored away from where 111 and 222 are. Another example is nested objects, where it's a safe bet that the "inner" object will be a separate block of memory, e.g. in foo = {a: 1, b: 2, nested: {inner: 1, object: 2}}, the foo object will have a pointer to the nested object. At the same time, the numbers variable in your example clearly must point at something in memory, so there's always one memory address that represents the object; it's just that parts of that object may possibly be an indirection away from there.

jmrk
  • 34,271
  • 7
  • 59
  • 74
  • Thanks, I was thinking that nested objects probably would have their own space but also thought grouping everything in one place might offer performance benefits so perhaps it's always one big group. – j obe Jan 10 '21 at 17:06