JavaScript memory management mechanism

JavaScript Memory Management mechanism

The core content of this paper comes from MDN Memory Management

Memory life cycle

The memory life cycle is the same in most programming languages, as shown in the figure below

  1. Allocate memory
  2. Read / write memory value
  3. Release memory when memory is no longer used

The second step is well defined in all programming languages. The first and last steps are managed manually in low-level languages and automatically in high-level languages.

  • Manual memory management. Low level languages such as C and C + + require programmers to explicitly operate memory allocation and memory release instructions, such as malloc() and free()
  • Automatic memory management. High level languages, such as JavaScript, can automatically allocate and free memory.

JavaScript memory management

1. Memory allocation

  • Value initializes allocated memory
var n = 123; // allocates memory for a number
var s = 'azerty'; // allocates memory for a stringvar 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);
  • Allocate memory through the object returned by the function call
var d = new Date(); // allocates a Date object

var e = document.createElement('div'); // allocates a DOM element

2. Use values in memory

Read and write the value of a variable or the property of an object in memory

let a = 1 //allocate memory
let b = 3 //allocate memory
console.log(a + b) //using values in memory

let obj = {
  name: 'Joe',
} //allocate memory

obj.name = 'Emily' //using values in memory

3. Memory release

The hardest part of memory release is to determine that the allocated memory is no longer used. This is where most memory management problems occur. JavaScript automatically releases memory that is no longer needed through garbage collection. It is undecidable to determine whether memory is no longer needed. In other words, no algorithm can accurately predict whether memory is no longer needed in all cases.

garbage collection

The commonly used algorithms for garbage collection implement reference counting and mark and sweep algorithms

1. Reference counting

This is the simplest garbage collection algorithm. The principle is to count the number of times other objects reference an object. If the number of references is 0, that is, no object references the object, it can be determined that the object is no longer needed and can be recycled.

var x = { //External object is x referenced
  a: { //Internal objects are referenced as properties of external objects
    b: 2
  }
};

var y = x;      // y refers to external objects, number of references + 1

x = 1;          // x reassigned, number of references to external object - 1

var z = y.a;    // z refers to the properties of the external object, that is, the internal object. Internal object references + 1

y = 'mozilla';  // y is re assigned, and the number of external object references is - 1, which is 0. At this time, the external object can be garbage collected, but its attribute a is referenced by z and cannot be released
z = null;       // z re assignment, internal object references - 1, 0. External objects are garbage collected

Limitations: circular references

Circular references refer to each other among objects to form a cycle, resulting in the internal existence that cannot be released after use. See the following example. According to the reference statistics algorithm, the number of references of X and Y is 1. Even if the two objects are no longer needed, they cannot be released. Circular references often cause memory leaks

function f() {
  var x = {};
  var y = {};
  x.a = y;        // x refers to y
  y.a = x;        // y refers to x

  return 'azerty';
}

f();

2. Mark and sweep algorithm

The principle is to assume that some objects are root objects. Starting from the root object, find all objects 1 that reference the root object, then find all objects that reference object 1, and so on. This process is similar to BFS (width first search). Through this method, all traversed objects are considered reachable, while other objects not traversed are unreachable, which will be recycled. In JavaScript, the root object is a global object For example, 'windows'. This algorithm is a commonly used garbage collection algorithm. In the above example, after the function call returns, X and y no longer have any direct or indirect contact with the global object, so they are recycled.

The algorithm is divided into two stages

  1. mark stage. After the object is created, it is marked as 0 (false) by default. During the traversal from the root object, the traversed object is marked as 1 (true).
  2. sweep phase. After the traversal is completed, the object marked 0 will be recycled.

The V8 engine has an out of memory problem

V8 engine is used for chrome browser and node, and provides a running environment to execute JavaScript code.
Check the memory problems through - expose GC -- inspect

Increase the size of heap memory by - Max old space size = < 6000 >

node --max-old-space-size=6000 index.js

node --expose-gc --inspect index.js

Tags: Javascript memory management

Posted on Sat, 25 Sep 2021 15:17:31 -0400 by nightkarnation