j obe
j obe

Reputation: 2039

In JS memory are objects stored as a block?

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.

Upvotes: 1

Views: 397

Answers (1)

jmrk
jmrk

Reputation: 40501

(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.

Upvotes: 4

Related Questions