Search code examples
javascriptnode.jsmemorymemory-managementv8

How does JavaScript(or NodeJS) handle memory allocation?


Assume V8 context.

Lets say an element of Number type has a size of 4 bytes.

Now, if I have an array,

let a = [1,2,3,4,5];

Logically speaking, the starting addresses of blocks for each element should be 1000,1004,1008,1012,1016

Now, lets say we have a string TestString which takes 10 bytes, and I do:

a[2] = 'TestString';

Such that the array becomes [1,2,'TestString',4,5].

How does JS handle the memory allocation of TestString and managing the address space of blocks in the array?


Solution

  • An array in JavaScript is really just a special type of object. As such, the "indexes" of the array are really just properties storing an integer value, and the data being stored are just pointers to the allocated memory blocks-- very much like a linked list.

    This is why you can use array methods like push or pop on the existing array without re-allocating the block of memory set aside for the array.

    I don't know the exact details of what V8 is doing, but I'm going to assume because of JavaScript's loosely/dynamically typed nature, it's probably not allocating memory contiguously like you used in your example-- there are just too many potential drawbacks to that for such a weak and dynamically typed language.

    JavaScript basically makes everything an object. An array is an object, the index values of the array, just pointers to objects. Which is why every data type is a variable and has access to properties and methods.

    In reality, the address spaces of:

    let a = [1, 2, 3, 4, 5];
    

    Would be pointers to the allocated memory blocks such as 548995, 48885, 3889282, 093838, 7883344. Or something like that. When you re-allocate any of them, JavaScript will find a block of memory in the heap and set the array index value to the allocated block's pointer.