JavaScript memory leaks

1. JavaScript's garbage collection mechanism

The most commonly used JavaScript garbage collection is marked with clear (mark-and-sweep). When a variable enters the environment (for example, a variable is declared in a function), the variable is marked as "into the environment". Logically speaking, the memory occupied by variables entering the environment can never be released, because they may be used as long as the execution flow enters the corresponding environment. And when the variable leaves the environment, this marks it as "Leave Environment".

function test(){
    
    
    let a = 10 ;       // 被标记 ,进入环境 
    let b = 20 ;       // 被标记 ,进入环境
}
test();  

2. What is a memory leak?

When the application no longer needs to occupy the memory, due to some reasons, the memory is not reclaimed by the system

Three. Common js memory leaks?

1. Unexpected global variables

//"use strict"
foo()
function foo(){
    
    
    word = "this is a global variable"
}
console.log(word);

Accidentally created a global variable, mounted on the window, use "use strict" to enable strict mode
2. Timer (setInterval)
uses clearInterval to cancel

var someResource = new Date().toLocaleString();
setInterval(function() {
    
    
    var node = document.getElementsByTagName('body');
    if(node) {
    
    
        node.innerHTML = JSON.stringify(someResource);
    }
}, 1000)

3. Binding the listener event addEventListener
uses removeEventListener to remove the corresponding listener event when the page is destroyed

Will closures cause memory leaks?

The correct answer is no.
Memory leak refers to variables that you can't use (can't access), still occupy memory space and cannot be reused.
The variables in the closure are the variables we need, which cannot be said to be a memory leak.

How did this misunderstanding come from? Because of IE. IE has a bug. After we use the closure, IE still cannot reclaim the variables referenced in the closure. This is an IE problem, not a closure problem. Refer to this article

Guess you like

Origin blog.csdn.net/m0_48076809/article/details/106697682