Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are JavaScript arrays stored in memory

So, I was thinking how arrays are stored in memory in JavaScript.

I already read How are JavaScript arrays represented in physical memory? , but I couldn't find my answer.

What I'm thinking is more about the memory location of the array units. In C for example, you need to define the size of the array when you define them. With this, C defines a whole block of memory, and it can look the exact location of each unit.

For example:

int array[10]; // C knows the memory location of the 1st item of the array

array[3] = 1   // C can do that, because it can calculate the location 
               // of array[3] by doing &array + 3 * (int size)

In JS, you can grow the size of an array after allocating memory to other stuff, which means JS doesn't work with the "block" type of array.

But if arrays are not a single block of memory, how does JS calculate where each unit is? Do JS arrays follows a linked list type of structure?

like image 615
João Haas Avatar asked Apr 23 '18 22:04

João Haas


People also ask

How is array stored in memory JavaScript?

In C for example, you need to define the size of the array when you define them. With this, C defines a whole block of memory, and it can look the exact location of each unit. In JS, you can grow the size of an array after allocating memory to other stuff, which means JS doesn't work with the "block" type of array.

How are arrays represented in memory?

Arrays are often represented with diagrams that represent their memory use. The diagram below is one typical way to represent the memory used by an array. Each box represents the amount of memory needed to hold one array element. For ints this is usually 4 bytes.

How are JavaScript objects stored in memory?

The heap is a different space for storing data where JavaScript stores objects and functions. Unlike the stack, the engine doesn't allocate a fixed amount of memory for these objects. Instead, more space will be allocated as needed. Allocating memory this way is also called dynamic memory allocation.

How are arrays stored in memory?

An array is just a group of integer, saved in the memory as single integer, but in one row. A integer has 4-Byte in the memory, so you can access each value of your array by increasing your pointer by 4.


Video Answer


1 Answers

One thing I would recommend everyone is that node.js recently became a first-class citizen of Chrome V8, so I would recommend studying V8 to see not only how it handles these implementation details but also why.

First, This article should prove beneficial to readers because of its focus on writing optimized isomorphic JavaScript:

https://blog.sessionstack.com/how-javascript-works-inside-the-v8-engine-5-tips-on-how-to-write-optimized-code-ac089e62b12e

The above article goes into details about how the JIT (Just In Time) compiler works, so you should be able to derive the exact questions you have after reading it.

Here is an exerpt:

Arrays: avoid sparse arrays where keys are not incremental numbers. Sparse arrays which don’t have every element inside them are a hash table. Elements in such arrays are more expensive to access. Also, try to avoid pre-allocating large arrays. It’s better to grow as you go. Finally, don’t delete elements in arrays. It makes the keys sparse.

Second, I would also recommend reading this and then working outward with respect to V8: http://www.jayconrod.com/posts/52/a-tour-of-v8-object-representation

Third, as a matter of critical bonus facts, I read this answer a while ago and I mentally revisit it from time to time. I am extremely surprised I just found it now. I literally Googled "stack overflow optimize train tracks" and found it. Thanks Google: Why is it faster to process a sorted array than an unsorted array?

Yes, that answer does have 27,000 positive votes.

That article talks about branch prediction, and I would like you to be aware of that because it could have some implications on how you work with data in general not just arrays. Again, note the first article I linked, and pay attention while it is describing the order of keys on an Object.

Performance can be optimized by understanding the implementation details and understanding why the problems were solved that way.

Finally, everything is an Object in JavaScript unless it is a scalar value, which we call primitives--String, Number, Boolean, etc.

Here is an example for thought provoking purposes:

const arr = ['one', 'two', 'three']

const sameArr = {
  0: 'one',
  1: 'two',
  2: 'three',
}

We could then destructure our Array as if it were an Object:

const yolo = ['one', 'two', 'three']

const {
  0: one,
  1: two,
  2: three,
} = yolo

console.log('Pretty cool:', one, two, three)

You can get some hints from that example as to why changing the order of keys could wreak havoc on the underlying hash table. Just because you can't see the keys doesn't mean they aren't there and affected.

In the above example, if it were a map, you could do sameArr.get('0') and JavaScript would reasonably know exactly where that is in the numerical table.

I would also recommend being careful reading old JavaScript material because of the overhauls of ES6. I feel the most comfortable directing you to V8 material.

like image 53
agm1984 Avatar answered Oct 17 '22 21:10

agm1984