What is a memory leak

Memory leak refers to the fact that the dynamically allocated heap memory in the program is not released or cannot be released due to some reason, resulting in the waste of system memory, slowing down the program, or even crashing the system.

2. Front-end memory leaks

1. Accidentally declare global variables

function name() {
name = 'hsy' 
}
Copy the code

Name is not declared. In JS, if the variable is not initialized, it defaults to global scope. Name is window.name. In the window variable, the name will not disappear as long as the window itself is not cleaned, so the solution is to use a keyword like let var const before name

2. The timer causes memory leaks

 let sex ='girl'
setInterval(() => {
	console.log(sex);
}, 1000); 
Copy the code

Cause of memory leak: The timer is always running and the name in the callback function is always occupying memory. The garbage collection mechanism knows this because it does not clean up external variables. Solution: Clear timer, clearInterval()

Closures cause memory leaks

let count = function() {
  let name = 'wyx'
  return function () {
    console.log(name);
    return name
  }
Copy the code

Cause of memory leak: Name will not be cleaned up in the presence of count because the closure always references name, causing more trouble if name has a lot of data. Let count = null; if not, set count to null, the next garbage collection will be directly collected.