JavaScript Advanced Programming Reading Sharing Chapter 4 - 4.3 Garbage Collection

JavaScript Advanced Programming (4th Edition) Reading Sharing Note Recording

Applicable to comrades who are just getting started

4.3.3 Performance

The garbage collection program runs periodically. If many variables are allocated in the memory, it may cause performance loss, so the garbage collection process
Timing is important. Especially on mobile devices with limited memory, garbage collection can significantly slow down rendering and frame rates. Developers don't know when the runtime will collect garbage, so the best way is to do it when writing the code: no matter when garbage collection starts, it can let it finish working as soon as possible.

memory leak

Poorly written JavaScript can have subtle and harmful memory leaks. On devices with limited memory, or in situations where functions are called many times, memory leaks can be a big problem. Most memory leaks in JavaScript are caused by unreasonable references.
  • Accidentally declaring a global variable is the most common and easiest to fix memory leak.
function setName() { 
 name = 'Jake'; 
}
At this point, the interpreter will create the variable name as an attribute of window (equivalent to window.name = 'Jake' ).
It is conceivable that the properties created on the window object will not disappear as long as the window itself is not cleaned up . This problem is easy to solve, just add the var , let , or const keyword before the variable declaration , so that the variable will leave the scope after the function is executed.
  • Timers can also quietly cause memory leaks.
let name = 'Jake'; 
setInterval(() => { 
 console.log(name); 
}, 100);
As long as the timer keeps running, the name referenced in the callback function will always occupy memory . The garbage collector knows this of course, so it doesn't clean up external variables.
  • It's easy to unknowingly create memory leaks with JavaScript closures.
let outer = function() { 
 let name = 'Jake'; 
 return function() { 
 return name; 
 }; 
};
Calling outer() will cause the memory allocated to name to be leaked. After the above code is executed, an internal closure is created, as long as it returns
The existence of the function of the name cannot be cleaned up , because the closure has been referencing it. If the content of name is large (more than just a small string), it may be a big problem.

Guess you like

Origin blog.csdn.net/weixin_42307283/article/details/129141631