Home >Web Front-end >JS Tutorial >How to solve the garbage collection mechanism and common memory leak problems in JS elevation
This article mainly introduces how to solve the garbage collection mechanism and common memory leak problems in JS elevation. It has certain reference value. Now I share it with you. Friends in need can refer to it
The reason for this is because I wanted to understand the memory leak mechanism of closures, and then I remembered the analysis of the garbage collection mechanism in "JS Advanced Programming". I didn't understand it very well before, but I will understand it when I look back after a year. , write to share with everyone. If you like it, you can like/follow and support it.
Allocate the memory you need:
Due to string, object There is no fixed size. Every time a js program creates a string or object, the program will allocate memory to store that entity.
Do something with the allocated memory.
Release it when no longer needed Return:
When strings and objects are no longer needed, the memory occupied by them needs to be released. Otherwise, all available memory in the system will be consumed, causing the system to crash. This is the meaning of the garbage collection mechanism.
The so-called memory leak refers to: due to negligence or error, the program fails to release memory that is no longer used, resulting in a waste of memory.
In languages such as C and C, memory needs to be managed manually, which is also the source of many unnecessary problems. Fortunately, in the process of writing js, memory allocation and memory recycling are completely automatically managed, and we don't have to worry about this kind of thing.
The garbage collector will periodically find variables that are no longer used at fixed time intervals, and then release the memory they occupy.
What is a variable that is no longer used?
Variables that are no longer used are variables that have ended their life cycle and are local variables. Local variables only exist during the execution of the function. When the function ends, there are no other references (closures). Then the variable will be marked for recycling.
The life cycle of global variables will not end until the browser unloads the page, which means global variables will not be treated as garbage collection.
Working principle:
When a variable enters the environment (for example, declaring a variable in a function), mark the variable as "Enter the environment", when a variable leaves the environment, it is marked as "leaving the environment". The memory marked "leaving the environment" is recycled.
Workflow:
The garbage collector will mark all variables stored in the memory during operation.
Remove the tags of variables in the environment and variables referenced by variables in the environment.
variables that still have tags are considered variables to be deleted.
destroy those marked values and reclaim the memory space they occupy.
all use the mark-and-sweep garbage collection strategy, but the garbage collection time intervals are different. There are different.
Reference counting omitted: obsolete garbage collection strategyCircular reference: a technique for tracking each value referencedIn older browsers (yes, IE again), BOM and DOM objects below IE9 are implemented in the form of COM objects using C. COM's garbage collection mechanism uses a reference counting strategy. This mechanism can never release memory when a circular reference occurs.var element = document.getElementById('something'); var myObject = new Object(); myObject.element = element; // element属性指向dom element.someThing = myObject; // someThing回指myObject 出现循环引用(两个对象一直互相包含 一直存在计数)。The solution is to manually cut off the links when we don't use them:
myObject.element = null; element.someThing = null;
Elimination:
IE9 removes BOM and DOM objects Converted to a real js object, avoiding the use of this garbage collection strategy, eliminating the main cause of common memory leaks below IE9. There is a performance issue with a confusing statement under IE7. Let’s take a look:global variables will not be treated as garbage collection. Sometimes the following situation occurs in our coding:
function foo() { this.bar2 = '默认绑定this指向全局' // 全局变量=> window.bar2 bar = '全局变量'; // 没有声明变量 实际上是全局变量=>window.bar } foo();
当我们使用默认绑定,this会指向全局,this.something
也会创建一个全局变量,这一点可能很多人没有注意到。
解决方法:在函数内使用严格模式or细心一点
function foo() { "use strict"; this.bar2 = "严格模式下this指向undefined"; bar = "报错"; } foo();
当然我们也可以手动释放全局变量的内存:
window.bar = undefined delete window.bar2
当不需要setInterval
或者setTimeout
时,定时器没有被clear,定时器的回调函数以及内部依赖的变量都不能被回收,造成内存泄漏。
var someResource = getData(); setInterval(function() { var node = document.getElementById('Node'); if(node) { node.innerHTML = JSON.stringify(someResource)); // 定时器也没有清除 } // node、someResource 存储了大量数据 无法回收 }, 1000);
解决方法: 在定时器完成工作的时候,手动清除定时器。
闭包可以维持函数内局部变量,使其得不到释放,造成内存泄漏。
function bindEvent() { var obj = document.createElement("XXX"); var unused = function () { console.log(obj,'闭包内引用obj obj不会被释放'); }; // obj = null; }
解决方法:手动解除引用,obj = null
。
就是IE9以下的循环引用问题,上文讲过了。
var refA = document.getElementById('refA'); document.body.removeChild(refA); // dom删除了 console.log(refA, "refA"); // 但是还存在引用 能console出整个p 没有被回收
不信的话,可以看下这个dom。
解决办法:refA = null;
过多的console,比如定时器的console会导致浏览器卡死。
解决:合理利用console,线上项目尽量少的使用console,当然如果你要发招聘除外。
记住一个原则:不用的东西,及时归还,毕竟你是'借的'嘛。
减少不必要的全局变量,使用严格模式避免意外创建全局变量。
在你使用完数据后,及时解除引用(闭包中的变量,dom引用,定时器清除)。
组织好你的逻辑,避免死循环等造成浏览器卡顿,崩溃的问题。
即使是1byte的内存,也叫内存泄漏,并不一定是导致浏览器崩溃、卡顿才能叫做内存泄漏。
一般是堆区内存泄漏,栈区不会泄漏。
基本类型的值存在内存中,被保存在栈内存中,引用类型的值是对象,保存在堆内存中。所以对象、数组之类的,才会发生内存泄漏。
使用chorme监控内存泄漏,可以看一下这篇文章
了解了内存泄漏的原因以及出现的情况,那么我们在编码过程中只要多加注意,就不会发生非常严重的内存泄漏问题。
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
原生JS基于window.scrollTo()封装垂直滚动动画工具函数
The above is the detailed content of How to solve the garbage collection mechanism and common memory leak problems in JS elevation. For more information, please follow other related articles on the PHP Chinese website!