w.brian
w.brian

Reputation: 17417

How are untyped javascript arrays laid out in memory considering they're not homogeneous?

I'm curious about the performance characteristics of untyped javascript arrays since they're not homogeneous, and was wondering how that is dealt with internally.

For example, if I have a number and some arbitrary object in an array, are they stored contiguously in memory? Are all primitives boxed and the array just contains pointers to everything? Is it an implementation detail of the VM?

Upvotes: 0

Views: 121

Answers (2)

rustyx
rustyx

Reputation: 85541

It depends on the JavaScript engine implementation.

But in general in JavaScript arrays, integers and floats are stored by-value and all other objects by-reference.

In V8 the array type will be either PACKED_ELEMENTS or HOLEY_ELEMENTS (depending on how the array was created/populated) and each string will additionally be stored separately on the heap.

To verify, use the %DebugPrint function in a debug version of the V8 engine (you can get one using jsvu tool):

d8> var a = [1, 2, 'aaa']; %DebugPrint(a);
DebugPrint: 000003B13FECFC89: [JSArray]
 - elements: 0x03b13fecfc31 <FixedArray[3]> {
           0: 1
           1: 2
           2: 0x00c73b3e0fe1 <String[#3]: aaa>
 }

Upvotes: 1

Teddy
Teddy

Reputation: 4253

Ryan Peden seems to have done some checking on all the juicy details (and fairly recently):

https://ryanpeden.com/how-do-javascript-arrays-work-under-the-hood/

Upvotes: 1

Related Questions