


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
Preface
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.
Memory life cycle:
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.
Garbage collection mechanism:
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.
Principle of the garbage collection mechanism:
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.
Mark clearing: the currently adopted garbage collection strategy
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.
- Those
variables that still have tags are considered variables to be deleted.
- Finally, the garbage collector will perform the final step of memory clearing,
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:- 256 variables, 4096 object (or array) literals or 64KB strings, Reaching any critical value triggers the garbage collector to run.
- If a js script keeps so many variables throughout its life cycle, the garbage collector will keep running frequently, causing serious performance problems.
What situations can cause memory leaks? Although there is a garbage collection mechanism, when we write code, some situations will still cause memory leaks. If we understand these situations and pay attention to avoid them when writing programs, our programs will be more robust. . Unexpected global variables: We mentioned above that
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以下的循环引用问题,上文讲过了。
没有清理DOM元素引用:
var refA = document.getElementById('refA'); document.body.removeChild(refA); // dom删除了 console.log(refA, "refA"); // 但是还存在引用 能console出整个p 没有被回收
不信的话,可以看下这个dom。
解决办法:refA = null;
console保存大量数据在内存中。
过多的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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool