On the blackboard

  1. What is a memory overflow?
    • An error that occurs when a program is running.
    • An out-of-memory error occurs when the program needs more memory to run than is available.
  2. What is a memory leak?
    • The occupied memory is not released in time.
    • The accumulation of memory leaks is easy to lead to memory overflow.
    • Common memory leaks: unexpected global variables, timers or callbacks that are not cleaned up in time, closures.

Here’s an example to help you understand

Out of memory

const obj = {}
for (var i = 0; i < 100000000; i++) {
   obj[i] = new Array(100000000)
   console.log('-----------------')
}
Copy the code

Because the number of loops is too large, resulting in insufficient physical memory, some small rich people set the value of the loop is larger.

Memory leaks

1. Unexpected global variables

function fn1() {
  a = 1
  console.log(a)
}
fn1()
Copy the code

When the function is executed, a becomes a global variable due to variable promotion, and a still occupies space after the function is executed

  1. Timer is not off
const intervalTime = setInterval(function () {
    console.log("------")
 }, 2000)
Copy the code

Because the timer was not turned off, memory overflow will continue until the browser is closed and refreshed.

Keep good habits and close them when you’re done

ClearInterval (intervalTime) // Disable the timer to release memoryCopy the code
  1. closure
function fn1() {
  let a = 2
   function fn2() {
      console.log(++a)
     }
   return fn2
  }
  const fn = fn1()
  fn()
Copy the code

A doesn’t get released after the function is executed, because fn saves fn1.

Remember to clear variables and wait for collection.

Fn = null // Free memoryCopy the code