Memory management of JavaScript Array [duplicate]

Asked
Active3 hr before
Viewed126 times

9 Answers

duplicatememoryarrayjavascript
90%

In the first version of JavaScript, there were no arrays. They were later introduced as a sub-class of that "mother of all objects": Object. You can test this quite easily by doing this:,Arrays are just an ordered list of objects. In JavaScript everything is an object, so arrays are not really arrays as we know them :),Possible Duplicate: Are Javascript arrays sparse? ,Arrays are objects, that allow you to reference their properties with numeric instances

In the first version of JavaScript, there were no arrays. They were later introduced as a sub-class of that "mother of all objects": Object. You can test this quite easily by doing this:

var foo = [1, 2, 3, 4];
for (var n in foo) { //check if n is equal (value and type) to itself, coerced to a number
   console.log(n === +(n) ? 'Number' : 'String');
}
load more v
88%

TypeError: can't delete non-configurable array element,ReferenceError: can't access lexical declaration`X' before initialization,In order to not bother the programmer with allocations, JavaScript will automatically allocate memory when values are initially declared.,Release the allocated memory when it is not needed anymore

var n = 123; // allocates memory for a number
var s = 'azerty'; // allocates memory for a string

var o = {
   a: 1,
   b: null
}; // allocates memory for an object and contained values

// (like object) allocates memory for the array and
// contained values
var a = [1, null, 'abra'];

function f(a) {
   return a + 2;
} // allocates a function (which is a callable object)

// function expressions also allocate an object
someElement.addEventListener('click', function() {
   someElement.style.backgroundColor = 'blue';
}, false);
load more v
72%

const sheeps = ['Apple', 'Banana', 'Juice'];

// Old way
const cloneSheeps = sheeps.slice();

// ES6 way
const cloneSheepsES6 = [...sheeps];
load more v
65%

A sizable set of allocations is performed.,We see our selected allocation is part of an array. In turn, the array is referenced by variable x inside the global window object. This gives us a full path from our big object to its noncollectable root (window). We found our potential leak and where it is referenced.,Another way in which an accidental global variable can be created is through this:,No further allocations are performed.

One of the objectives behind JavaScript was to develop a language that looked like Java but was permissive enough to be used by beginners. One of the ways in which JavaScript is permissive is in the way it handles undeclared variables: a reference to an undeclared variable creates a new variable inside the global object. In the case of browsers, the global object is window. In other words:

function foo(arg) {
   bar = "this is a hidden global variable";
}
load more v
75%

When we need to copy an array, we often times used slice. But with ES6, you can also use the spread operator to duplicate an array. Pretty nifty, right 🤩,Please note spread only goes one level deep when copying an array. So if you're trying to copy a multi-dimensional arrays, you will have to use other alternatives.,Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array and not the value of the array. To create a real copy of an array, you need to copy over the value of the array under a new value variable. That way this new array does not reference to the old array address in memory.,Stack Overflow: Why is a spread element unsuitable for copying multidimensional arrays?

const sheeps = ['🐑', '🐑', '🐑'];

// Old way
const cloneSheeps = sheeps.slice();

// ES6 way
const cloneSheepsES6 = [...sheeps];
load more v
40%

Arrays are objects as well, which is why they are stored in the heap.,"Objects" in the context of memory management doesn't only include JS objects but also functions and function scopes., JS allocates memory for this object in the heap. The actual values are still primitive, which is why they are stored in the stack., This creates a new object in the heap and a reference to it in the stack.

const person = {
   name: 'John',
   age: 24,
};
load more v
22%

V8 represents your objects in an object model. Objects are represented as associative arrays in JavaScript, but in V8 they are represented with hidden classes, which are an internal type system for optimized lookups., The Profile tab gives you information about your code’s performance.,As you can see above, a perfomance.memory property is also available that gives access to JavaScript memory usage data such as the total heap size., Test of empty literal versus pre-allocated array in various browsers.

In quite a few discussions online about reclaiming memory in JavaScript, the delete keyword is brought up, as although it was supposed to be used for just removing keys from a map, some developers think you can force de-referencing using it. Avoid using delete if you can. In the below example, delete o.x does a lot more harm than good behind the scenes, as it changes o’s hidden class and makes it a generic slow object.

var o = {
   x: 1
};
delete o.x; // true
o.x; // undefined
load more v
60%

Memory before the garbage collection,Memory after the garbage collection,Node.js Garbage Collection Explained [ this article ],Application-level memory management can be manual or automatic. The automatic memory management usually involves a garbage collector.

The following code snippet shows how memory can be allocated in C, using manual memory management:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {

   char name[20];
   char *description;

   strcpy(name, "RisingStack");

   // memory allocation
   description = malloc( 30 * sizeof(char) );
	
   if( description == NULL ) {
      fprintf(stderr, "Error - unable to allocate required memory\n");
   } else {
      strcpy( description, "Trace by RisingStack is an APM.");
   }
   
   printf("Company name = %s\n", name );
   printf("Description: %s\n", description );

   // release memory
   free(description);
}
load more v
48%

Set can remove any duplicates of the same object within an array but cannot detect that different objects have identical keys and values.,This past week, I ran into a problem while working on the reducer logic of my application. I needed to ensure the reducer was not adding duplicate data to state. Normally, I would utilize a Set to remove any duplicate values, but the data returned from my API was an array of JavaScript objects.,The final step was to optimize everything for Redux. While the above algorithm would work, I decided to store the dictionary in state, allowing the reducer to check only the new objects returned by my API call. This reduces the number of iterations needed to parse new data while only marginally increasing memory usage (A dictionary with key/value pairs that are strings and booleans takes up relatively little space).,A naive approach would utilize a nested loop to iterate through the collection, checking each element with the entire collection to see if a duplicate exists. This results in a time complexity of O(n²) and is woefully inefficient.

This past week, I ran into a problem while working on the reducer logic of my application. I needed to ensure the reducer was not adding duplicate data to state. Normally, I would utilize a Set to remove any duplicate values, but the data returned from my API was an array of JavaScript objects.

Set
load more v

Other "duplicate-memory" queries related to "Memory management of JavaScript Array [duplicate]"