


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 出现循环引用(两个对象一直互相包含 一直存在计数)。
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!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

React's main functions include componentized thinking, state management and virtual DOM. 1) The idea of componentization allows splitting the UI into reusable parts to improve code readability and maintainability. 2) State management manages dynamic data through state and props, and changes trigger UI updates. 3) Virtual DOM optimization performance, update the UI through the calculation of the minimum operation of DOM replica in memory.

Apache server is a powerful web server software that acts as a bridge between browsers and website servers. 1. It handles HTTP requests and returns web page content based on requests; 2. Modular design allows extended functions, such as support for SSL encryption and dynamic web pages; 3. Configuration files (such as virtual host configurations) need to be carefully set to avoid security vulnerabilities, and optimize performance parameters, such as thread count and timeout time, in order to build high-performance and secure web applications.

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

The Installation, Configuration and Optimization Guide for HDFS File System under CentOS System This article will guide you how to install, configure and optimize Hadoop Distributed File System (HDFS) on CentOS System. HDFS installation and configuration Java environment installation: First, make sure that the appropriate Java environment is installed. Edit /etc/profile file, add the following, and replace /usr/lib/java-1.8.0/jdk1.8.0_144 with your actual Java installation path: exportJAVA_HOME=/usr/lib/java-1.8.0/jdk1.8.0_144exportPATH=$J

Nginx performance monitoring and troubleshooting are mainly carried out through the following steps: 1. Use nginx-V to view version information, and enable the stub_status module to monitor the number of active connections, requests and cache hit rate; 2. Use top command to monitor system resource occupation, iostat and vmstat monitor disk I/O and memory usage respectively; 3. Use tcpdump to capture packets to analyze network traffic and troubleshoot network connection problems; 4. Properly configure the number of worker processes to avoid insufficient concurrent processing capabilities or excessive process context switching overhead; 5. Correctly configure Nginx cache to avoid improper cache size settings; 6. By analyzing Nginx logs, such as using awk and grep commands or ELK

To view the thread status in the Tomcat log, you can use the following methods: TomcatManagerWeb interface: Enter the management address of Tomcat (usually http://localhost:8080/manager) in the browser, and you can view the status of the thread pool after logging in. JMX Monitoring: Use JMX monitoring tools (such as JConsole) to connect to Tomcat's MBean server to view the status of Tomcat's thread pool. Select in JConsole

There are many ways to monitor the status of HDFS (Hadoop Distributed File System) on CentOS systems. This article will introduce several commonly used methods to help you choose the most suitable solution. 1. Use Hadoop’s own WebUI, Hadoop’s own Web interface to provide cluster status monitoring function. Steps: Make sure the Hadoop cluster is up and running. Access the WebUI: Enter http://:50070 (Hadoop2.x) or http://:9870 (Hadoop3.x) in your browser. The default username and password are usually hdfs/hdfs. 2. Command line tool monitoring Hadoop provides a series of command line tools to facilitate monitoring

Configuring an HTTPS server on a Debian system involves several steps, including installing the necessary software, generating an SSL certificate, and configuring a web server (such as Apache or Nginx) to use an SSL certificate. Here is a basic guide, assuming you are using an ApacheWeb server. 1. Install the necessary software First, make sure your system is up to date and install Apache and OpenSSL: sudoaptupdatesudoaptupgradesudoaptinsta
