1

I'm trying to understand how JS engines like V8 handle objects in arrays and specifically how is memory allocated and is it efficient.

I have an array that is with objects not sorted and I produce an array that has those same objects in a sorted array

let obj1 = {'test': 'test1'};
let obj2 = {'test': 'test2'};
let obj3 = {'test': 'test3'};

let arr1 = [obj1,obj3,obj2];

...Do sorting and create a new array (no I don't want to destroy the previous)
let arr2 = [obj1,obj2,obj3];

Is the memory overhead only in the references created between the indices and the objects or am I actually duplicating the objects in memory space?

George Kouzmov
  • 319
  • 4
  • 15
  • 5
    The only thing new is the array. The object references don't produce copies of those objects. You can verify this by modifying one of the objects in the array, and checking to see if the original object reference was modified too. It will be, because its the same object. –  Feb 07 '20 at 16:36
  • 1
    You have two arrays that contain the same object ref values in them. So, the size would be (roughly) `3* + `. – VLAZ Feb 07 '20 at 16:38
  • 3
    Objects are reference values. Unless you explicitly create a new object, everything will just copy the reference to the existing object contents. – Bergi Feb 07 '20 at 16:38
  • 2
    Does this answer your question? [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – VLAZ Feb 07 '20 at 16:38
  • This makes sense, thank you! – George Kouzmov Feb 07 '20 at 17:23

1 Answers1

1

In Spidermonkey, Mozilla's engine, an Array of Object will be represented by a C++ array of jsval. jsval are 64-bit quantities that, when representing JS Objects, are effectively pointers.

So the answer to your question is that the underlying representation is basically an array of pointers, which is about as effecient as you can get.

I say "basically", because once you start making an array with large sparse gaps, non-numerical properties, or a bunch of other things -- the engine will de-specialize it and basically store it like an object internally.

I haven't read this part of the v8 sources, but I'm confident the implementation is similar. Doing it like this is obvious once you're in there, and both engines perform pretty close to one another in terms of array property access.

Wes
  • 950
  • 5
  • 12