This article has participated in the third “topic writing” track of the Denver Creators Training Camp. For details, check out: Digg Project | Creators Training Camp third is ongoing, “write” to make a personal impact.


Note: Part of the article content and pictures from the network, if there is infringement please contact me (homepage public number: small siege lion learning front)

By: Little front-end siege lion, home page: little front-end siege lion home page, source: Nuggets

GitHub: P-J27, CSDN: PJ wants to be a front-end siege lion

Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.


Knowledge of the line

What is a memory leak? => What causes the memory leak? => How do I resolve memory leaks? => Garbage collection policy (two types) => How to manage memory?

Interviewer: What is a memory leak? Why does this cause memory leaks?

What is a memory leak?

A memory leak is when no longer needed memory is not released in time.

Why does this cause memory leaks?

A memory leak is when we can no longer refer to an object through js code, but the garbage collector thinks the object is still being referenced, so it will not be released at collection time.

As a result, the allocated chunk of memory can never be freed. If this happens more and more, the system will run out of memory and crash.

Garbage collection mechanism

JavaScript has automatic garbage collection (GC: GarbageCollecation), which means that the execution environment is responsible for managing the memory used during code execution. Developers no longer have to worry about memory usage, and the allocation of needed memory and the collection of unused memory are fully managed automatically.

Interviewer: How do you solve the memory leak? How does JS garbage collection work?

We need to manage the memory manually, but there is an automatic garbage collection mechanism for JS, automatic memory management.

Memory life cycle

Memory allocated in the JS environment generally has the following life cycle:

  1. Memory allocation: The system automatically allocates memory for variables, functions, and objects as they are declared and executed
  2. Memory usage: reading and writing memory, that is, using variables, functions, etc
  3. Memory reclamation: The garbage collection mechanism reclaims unused memory

Garbage collection mechanism policy

Mark clearing algorithm

The most common method of garbage collection in JavaScript is mark-and-sweep.

Its implementation principle is to determine whether a variable is referenced in the execution environment to carry out tag deletion.

The garbage collector marks all memory variables, then removes the execution environment and referenced tags. The remaining tag variables are unused variables and are collected by the garbage collector.

This algorithm simplifies the definition of “whether an object is no longer needed” to “whether an object is available”.

The algorithm assumes setting up an object called root (in Javascript, root is a global object). The garbage collector periodically scans for objects in memory, starting at the root (or global objects in JS). Anything that can be reached from the root is still needed. Objects that cannot be reached from the root are marked as unused and recycled later.

This algorithm can be divided into two stages, one is the mark stage and the other is the sweep stage.

  1. In the marking phase, the garbage collector iterates from the root object. An identity is added to each object that can be accessed from the root object, and the object is identified as reachable.
  2. In the garbage collector phase, the heap memory is traversed linearly from beginning to end. If an object is not identified as a reachable object, the memory occupied by the object is reclaimed and the identity previously marked as a reachable object is cleared for the next garbage collection operation.

In the marking phase, if the root object 1 can be accessed from B and from B to E, then B and E are reachable, and in the same way, F, G, J, and K are reachable.

During the collection phase, all objects not marked as reachable are collected by the garbage collector.

When does garbage collection start?

In general, unreferenced objects are not immediately reclaimed when the tag clearing algorithm is used. Instead, garbage objects accumulate until memory runs out. When memory runs out, the program is suspended and garbage collection begins.

Add: Since 2012, all modern browsers use the mark-sweep garbage collection algorithm. All of the improvements to JavaScript garbage collection algorithms are based on improvements to the mark-sweep algorithm, not on improvements to the mark-sweep algorithm itself and its simplified definition of whether an object is no longer needed.

Mark clearance algorithm defects
  • Objects that cannot be queried from the root object are cleared
  • Garbage collection can result in a large amount of memory fragmentation, as shown in the image above. After garbage collection, there are three memory fragments in memory. Assuming that one square represents one unit of memory, if an object occupies three units of memory, it will cause the Mutator to remain suspended. The Collector attempts garbage collection until it is Out of Memory.

Reference counting algorithm

This is the most rudimentary garbage collection algorithm. No browser now uses this algorithm.

This algorithm simplifies the definition of “whether an object is no longer needed” to “whether the object has other objects referring to it”. If there are no references to the object (zero references), the object will be collected by the garbage collection mechanism.

The meaning of reference counting is to keep track of how many times each value is referenced. When a variable is declared and a reference type value is assigned to the variable, the number of references to the value is 1. If the same value is assigned to another variable, the number of references to the value is increased by one. Conversely, if a variable containing a reference to that value obtains another value, the number of references to that value is reduced by one. When the number of references to this value goes to zero, there is no way to access the value, and the memory space it occupies can be reclaimed. This way, the next time the garbage collector runs, it frees the memory occupied by values with zero references.

Reference countingdefects

This algorithm has a limitation: it cannot handle circular references. If two objects are created and reference each other, a loop is formed. They leave function scope when called, so they are no longer useful and can be recycled. However, the reference-counting algorithm takes into account that they all have at least one reference to each other, so they are not recycled.

Chrome V8 recycle algorithm

See the Chrome V8 recycle algorithm

Garbage reduction and recycling impact on performance:

Pay attention to the following two points:

  • Keep garbage collection to a minimum, especially full heap collection. There is little we can do about this, relying on V8’s own optimizations.
  • Avoid memory leaks and release memory in a timely manner. How do you manage memory to avoid memory leaks

How to Manage Memory

One of the main problems with automatic memory management for JS is that the amount of available memory allocated to Web browsers is usually less than that allocated to desktop applications.

Strategies to avoid:

  1. Reduce unnecessary global variables, or objects with long life cycles, and timely garbage collection of useless data (i.e., null assignment);
  2. Pay attention to program logic, avoid “endless loop” and so on;
  3. Rule of thumb to avoid creating too many objects: Return what you don’t use.
  4. Reduce hierarchical references

To get the best performance out of a page, you must ensure that js variables take up the least amount of memory, and the best way to do this is to release unused variable references, also known as dereferencing.

  • Local variables: when the function leaves the environment variable after execution, the variable will be removed automatically.
  • Global variables: For global variables we need to remove them manually. (Note: Dereferencing does not mean being reclaimed, but actually taking the variable out of the execution environment and reclaiming it in the next garbage collection)
var a = 20; // Allocate space in stack memory for numeric variables
alert(a + 100); // Use memory
var a = null; // Free up memory space after use
Copy the code

Note: Only variables that have lost a reference to an environment variable are marked for collection. In this example, by setting the object’s reference to NULL, the variable is deprimed and waiting to be collected by the garbage collector.


Thank you for reading, I hope to help you, if there is a mistake or infringement of the article, you can leave a message in the comment area or add a public number in my home page to contact me.

Writing is not easy, if you feel good, you can “like” + “comment” thanks for your support ❤