Memory allocation of for the same objects in different arrays

417 Views Asked by At

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?

1

There are 1 best solutions below

0
Wes On

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.