This is the fourth day of my participation in Gwen Challenge

What is a memory leak

A memory leak is a memory leak caused when the used memory is not released during the release period of the life cycle. When a memory leak is severe, it can cause the entire system to stall or even crash.

Second, JavaScript memory management

In languages like C++, developers have direct control over memory allocation and reclamation. In JavaScript, however, memory is handled by the program itself, which means that JavaScript has an automatic garbage collection mechanism.

1. Memory life cycle

  • Allocation period Allocates the required memory during this period.

  • The usage life uses the allocated memory, that is, to perform read and write operations.

  • The free period is the period during which unwanted memory should be freed and returned.

2. Memory allocation

In JavaScript, assigning a value to a variable of a data type is an automatic memory allocation, such as:

let num = 123  // Allocate memory for numeric variables
const str = "ababa"  // Allocate memory to the string
const obj = {  // Allocate memory to the object
    name: "ababa".id: 1
}
const arr = [1.2.3] // Allocate memory to the array
function fn(param){ // Allocate memory to the function
    return param
}
Copy the code

3. Memory usage

As mentioned above, memory usage is the operation of reading and writing to allocated memory. Such as:

let num = 123  // Allocate memory for numeric variables
function fn(param){ // Allocate memory to the function
    return param
}

fn(num)  // Perform read and write operations
Copy the code

4. Memory release

To avoid memory leaks, let’s first look at the JavaScript garbage collection mechanism. Memory leaks usually occur during garbage collection. Although the memory reclamation mechanism of JavaScript can recycle most of the garbage memory, there are still some cases that can not be recycled. If these cases exist, we need to manually clean the memory.

5. JavaScript garbage collection

There are two common garbage collection mechanisms in JavaScript: tag scavenging and reference counting.

(1) Mark removal method

This is the most common method of garbage collection in JavaScript. That is, after the reference, the unused memory data is marked, and the garbage collector removes the marked variables.

(2) Reference counting method

Reference counting refers to the fact that the language engine has a “reference table” that holds the number of references to all resources (usually values) in memory. If the number of references to a value is zero, the value is no longer needed, so it can be freed.

Common scenarios for JavaScript memory leaks

(1) Forgotten timer

I often see many students around me write a lot of timer, but after defining the timer did not consider the clear timer. This can cause a certain amount of memory leakage.

  // The forgotten timer
  function f() {
      let obj = new Array(100000)
      setInterval(() = > {
          let myObj = obj
      },1000)}Copy the code

The above code is a typical way to use a timer, which will leak memory. The correct way to do this is:

  // The forgotten timer
  function f() {
      let obj = new Array(100000)
      let count = 0  // Use the counter
      let timer = setInterval(() = > {
          if (count === 5) clearInterval(timer);  // Clear the timer when the counter reaches the fifth time to prevent memory leaks
          let myObj = obj
          count++  // The counter is incremented by one after successful execution
      },1000)}Copy the code

(2) Printing of the console

Console printing can also cause memory leaks. It is common to write a lot of console during development, and it is important to delete these test statements after testing is complete.

(3) Unexpected global variables

What is an unexpected global variable? For example, let’s look at the following code

  function fn(num){
      basicNum = 1
      return basicNum+num
  }

  fn(2)
Copy the code

Global variables are not normally collected by the garbage collector, such as basicNum, which is undeclared and assigned directly, causing the memory space assigned to the global variable to persist. If you assign to a large array, the memory will be large.

In fact, if you do not pay attention to it at ordinary times, you can also open strict mode, so that you can detect when you do not pay attention to the error warning ⚠.

(4) Forgotten event listeners

We wrote a lot of useless event listeners during development, and forgetting to clean them up also caused a memory leak.

That’s the basics of JavaScript memory leaks