Frequently asked questions in front end interview: JS garbage collection mechanism

Huawei cloud developer community 2021-02-23 14:22:16
frequently questions end interview js


Abstract : as everyone knows , Applications need to occupy a certain amount of memory space in the process of running , And after running, we must release the memory that we no longer use , Otherwise, the memory consumption in the figure below will continue to increase , On the one hand, it will affect the running speed of the program , On the other hand, if it is serious, it will cause the whole program to crash .

as everyone knows , Applications need to occupy a certain amount of memory space in the process of running , And after running, we must release the memory that we no longer use , Otherwise, the memory consumption in the figure below will continue to increase , On the one hand, it will affect the running speed of the program , On the other hand, if it is serious, it will cause the whole program to crash .

 

 

JavaScript Memory management in

  • Memory : It is made up of read-write units , Represents an operable space ;
  • management : Man made application to operate a space 、 Use and release ;
  • memory management : Developers take the initiative to apply for space 、 Use space 、 Release space ;
  • Management process : apply - Use - Release

Part of the language needs ( for example C Language ) You need to release memory manually , But it's going to be a lot of trouble , So many languages , for example JAVA Will provide automatic memory management mechanism , be called “ Garbage collection mechanism ”,JavaScript The language also provides a garbage collection mechanism (Garbage Collecation), abbreviation GC Mechanism .

A complete pause (Stop The World )

Before introducing the garbage collection algorithm , Let's get to know 「 A complete pause 」. Before the garbage collection algorithm is executed , The application logic needs to be suspended , Execute the application logic after garbage collection , This behavior is called 「 A complete pause 」(Stop The World). for example , If a GC need 50ms, The application logic will pause 50ms.

The purpose of total pause , It is to solve the problem that the application logic is inconsistent with what the garbage collector sees .

for instance , Eating in a cafeteria , When I come back from happily taking food , It turned out that the waiter had taken away his cutlery . here , Waiters are like garbage collectors , Tableware is like the object of distribution , We're just applying logic . In our view , Just put the tableware on the table , But the waiter seems to think you don't need to use it anymore , So I took it away . You and the waiter don't see the same thing in the same way , It caused the waiter to do something we didn't expect . therefore , To avoid inconsistency between the application logic and what the garbage collector sees , When the garbage collection algorithm is executed , Need to stop applying logic .

JavaScript Garbage collection in

JavaScript The cases that will be judged as garbage in the project are as follows :

  • Object is no longer referenced ;
  • Object cannot be accessed from the root ;

GC Algorithm

common GC Algorithm is as follows :

  • Reference count
  • Mark clear
  • Tag to sort out
  • Generational recycling

Reference count

The most common garbage collection method used by early browsers was called " Reference count "(reference counting): The language engine has a " Reference table ", Save all the resources in memory ( It's usually a variety of values ) The number of citations . If the number of references to a value is 0, It means that this value is no longer used , So this memory can be released .

const user1 = {age: 11}
const user2 = {age: 22}
const user3 = {age: 33}
const userList = [user1.age, user2.age, user3.age]

The above code , When it's done all over again ,user1、user2、user3 It's all about being userList Refer to the , So their reference count is not zero , It won't be recycled

function fn() {
const num1 = 1
const num2 = 2
}
fn()

In the above code fn The function is finished ,num1、num2 All local variables , After execution , Their reference counts are all zero , All this code will be treated as “ The garbage ”, To recycle .

The reference counting algorithm has a big problem :  Circular reference

function objGroup(obj1, obj2) {
obj1.next = obj2
obj2.prev = obj1
return {
o1: obj1,
o2: obj2,
}
}
let obj = objGroup({name: 'obj1'}, {name: 'obj2'})
console.log(obj)

In the example above ,obj1 and obj2 They refer to each other through their own attributes , All of them have non-zero reference counts , So it won't be recycled by the garbage collection mechanism , Memory waste .

In fact, the reference counting algorithm has a big disadvantage , That is, we need a separate space to maintain the reference count of each variable , For larger programs , The space cost is relatively large .

The advantages of reference counting algorithm :

  • When the reference count is zero , If you find garbage, recycle it immediately ;
  • Minimize program pauses ;

Disadvantages of reference counting algorithm :

  • Can't recycle circular references ;
  • The space cost is quite large ;

Mark clear (Mark-Sweep)

The core idea : It is divided into two stages: marking and clearing .

  1. Traverse all objects to find the active object ;
  2. Traverse all objects, clear unmarked objects ;
  3. Reclaim the space .

The advantage of the tag clearing algorithm is : Compare the reference counting algorithm , The biggest advantage of the tag cleaning algorithm is that it can recycle the object of circular reference , So is it v8 The engine uses the most algorithms .
The drawback of the tag clearing algorithm is :

 

 

As we can see in the picture above , The red area is a root object , It's a global variable , Will be marked ; And the blue area is the unmarked object , Will be recycled by the recycling mechanism . And then there's a problem , The blue area on the surface is recycled into three spaces , But these three spaces are discontinuous , When we have an object that needs three spaces , So the space we just reclaimed can't be allocated , This is it. “ Space fragmentation ”.

Tag to sort out (Mark-Compact)

To solve the problem of memory fragmentation , Improve the use of memory , Tag sorting algorithm is introduced .

Mark collation can be regarded as mark clearing enhance . The operation of the tag phase is consistent with the tag cleanup .

The clean-up phase starts with the clean-up phase , Move object position , Move the living object to one side , Then clean up the memory outside the end boundary .

 

 

 

 

 

 

The drawback of tagging is : Move object position , Objects are not immediately recycled , The efficiency of recycling is relatively slow .

Increment mark (Incremental Marking)

To reduce the total pause time ,V8 Tags are optimized , The marking process that takes a pause , It's a lot of small steps . Let the application logic run for a while after each small step , This alternates many times to complete the marking .

 

 

For a long period of time GC, Will cause the application to pause and not respond , It's going to lead to a bad user experience . from 2011 From the year onwards ,v8 will 「 Full pause 」 The tag is replaced by an incremental tag . The improved marking method , The maximum pause time is reduced to the original 1/6.

v8 Engine garbage collection strategy

  • Adopt the idea of generational recycling ;
  • Memory is divided into new generation 、 Old generation ;

Different algorithms are used for different objects :
(1) The new generation : The survival time of the object is shorter . New objects or objects that have only been garbage collected once .
(2) Old generation : The object has a longer survival time . Objects that have experienced one or more garbage collections .

 

 

V8 The space of the pile is equal to the space of the Cenozoic plus the space of the old generation . And for different operating systems, the space is limited by memory .

 

 

For browsers , That's enough memory . The reason for limiting memory :

Browser specific GC Mechanism , After constant testing , If the memory is set a little bit larger ,GC The recycling time will reach the user's perception , It's going to cause perceptual stumbling .

Recycling new generation objects

Recycling of new generation objects mainly adopts Copy algorithm Scavenge Algorithm ) Tag sorting algorithm . and Scavenge Algorithm The concrete realization of , Mainly adopted Cheney Algorithm .

 

 

Cheney Algorithm Divide memory into two equal spaces , Use space for From, The free space is To.

Check From Living objects in space , If the object survives , Check whether the target is qualified for promotion , If they meet the requirements, they will be promoted to the old generation , Otherwise, from the object  From  Space copied to  To  Space . If the object doesn't survive , Then release the space of the non living objects . Once the copy is done , take  From  Space and  To  Space for character flipping .

Object promotion mechanism

Round GC The surviving new generation needs to be promoted .
When the object from From  Space copied to  To  When space , if  To  Space use exceeds 25%, Then the object is promoted directly to the old generation . Set to 25% The reason for this is , When finished  Scavenge  After recycling ,To  The space will flip into From  Space , Continue to allocate object memory . If the proportion is too large , Will affect subsequent memory allocation .

Recycling old generation objects

Recycling of old generation objects mainly uses Mark clear Tag to sort out Increment mark Algorithm , The main use of Mark clear Algorithm , Only when memory allocation is insufficient , use Tag to sort out Algorithm .

  1. use first Mark clear Complete the garbage space Recycling ;
  2. use Tag to sort out Conduct Space optimization ;
  3. use Increment mark Conduct Efficiency optimization ;

A comparison between Cenozoic and old generation recycling

The new generation takes up less space , Using the space for time mechanism .
The space of the old generation is relatively large , It's not suitable for a lot of copy algorithms and tag collation , So the most common is Mark clear Algorithm , In order to minimize the total pause time .

Memory leak identification method

Let's start with a piece of memory consuming code :

<button class="btn"> Click on </button>
<script>
const btn = document.querySelector('.btn')
const arrList = []
btn.onclick = function() {
for(let i = 0; i < 100000; i++) {
const p = document.createElement('p')
// p.innerHTML = ' I am a p Elements '
document.body.appendChild(p)
}
arrList.push(new Array(1000000).join('x'))
}
</script>

Using the browser Performance To monitor memory changes

 

 

Click record , And then we feel that the operations that consume performance , After the operation , Click on stop Stop recording .

 

 

Then let's take a look at the places that caused the memory leak , We just need to focus on memory .

 

 

We can see that the memory consumption is faster in a short time , The small recesses of the descent , The browser is garbage collection .

performance optimization

1. Avoid using global variables

  • Global variables are mounted on window Next ;
  • Global variables have at least one reference count ;
  • Global variables live longer , Continuously occupying memory ;
  • With clear data scope , Try to use local variables ;

2. Reduce the level of judgment

function doSomething(part, chapter) {
const parts = ['ES2016', ' engineering ', 'Vue', 'React', 'Node']
if (part) {
if (parts.includes(part)) {
console.log(' Belongs to the current course ')
if (chapter > 5) {
console.log(' You need to provide VIP identity ')
}
}
} else {
console.log(' Please confirm the module information ')
}
}
doSomething('Vue', 6)
// Reduce the level of judgment 
function doSomething(part, chapter) {
const parts = ['ES2016', ' engineering ', 'Vue', 'React', 'Node']
if (!part) {
console.log(' Please confirm the module information ')
return
}
if (!parts.includes(part)) return
console.log(' Belongs to the current course ')
if (chapter > 5) {
console.log(' You need to provide VIP identity ')
}
}
doSomething('Vue', 6)

3. Reduce the number of data reads
For frequently used data , We need to cache the data .

<div id="skip" class="skip"></div>
<script>
var oBox = document.getElementById('skip')
// function hasEle (ele, cls) {
// return ele.className === cls
// }
function hasEle (ele, cls) {
const className = ele.className
return className === cls
}
console.log(hasEle(oBox, 'skip'))
</script>

4. Reduce activity in the circulatory system

var test = () => {
var i
var arr = ['Hello World!', 25, ' How can it be said that you have nothing to wear? , I will share my long robes with you. ']
for(i = 0; i < arr.length; i++) {
console.log(arr[i])
}
}
// After optimization , take arr.length Put forward separately , Prevent getting it once per loop 
var test = () => {
var i
var arr = ['Hello World!', 25, ' How can it be said that you have nothing to wear? , I will share my long robes with you. ']
var len = arr.length
for(i = 0; i < len; i++) {
console.log(arr[i])
}
}

5. Event binding optimization

<ul class="ul">
<li>Hello World!</li>
<li>25</li>
<li> How can it be said that you have nothing to wear? , I will share my long robes with you. </li>
</ul>
<script>
var list = document.querySelectorAll('li')
function showTxt(ev) {
console.log(ev.target.innerHTML)
}
for (item of list) {
item.onclick = showTxt
}
// After optimization 
function showTxt(ev) {
var target = ev.target
if (target.nodeName.toLowerCase() === 'li') {
console.log(ev.target.innerHTML)
}
}
var ul = document.querySelector('.ul')
ul.addEventListener('click', showTxt)
</script>

6. Avoid closure traps

<button class="btn"> Click on </button>
<script>
function foo() {
let el = document.querySelector('.btn')
el.onclick = function() {
console.log(el.className)
}
}
foo()
// After optimization 
function foo1() {
let el = document.querySelector('.btn')
el.onclick = function() {
console.log(el.className)
}
el = null // take el Set as null Prevent references in closures from being recycled 
}
foo1()
</script>

This article is shared from Huawei cloud community 《Vue Advanced ( Lu Jiu ):JS Garbage collection mechanism 》, Original author :SHQ5785 .

Click to follow , The first time to learn about Huawei's new cloud technology ~

版权声明
本文为[Huawei cloud developer community]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/02/20210223141900757h.html

  1. 对前端异常window error捕获的全面总结
  2. A comprehensive summary of front end exception window error capture
  3. 成功解决Problem while trying to mount target]\“. HTTP response code is 400
  4. Problem while trying to mount target] \ ". HTTP response code is 400
  5. 放弃okhttp、httpClient,选择了这个牛逼的神仙工具!贼爽
  6. 前端面试每日 3+1 —— 第679天
  7. How to add elements at the beginning of an array in JS?
  8. Give up okhttp and httpclient and choose this awesome immortal tool! Thief Shuang
  9. Front end interview daily 3 + 1 - day 679
  10. 【2021 第一期】日常开发 26 个常见的 JavaScript 代码优化方案
  11. Daily development of 26 common JavaScript code optimization schemes
  12. 前端的字符串时间如何自动转换为后端Java的Date属性,介绍springMVC中如何解决时间转换问题
  13. How to automatically convert the front-end string time to the back-end Java date attribute, and how to solve the time conversion problem in spring MVC are introduced
  14. 前端面试常考题:JS垃圾回收机制
  15. ReactDOM.render串联渲染链路(一)
  16. 更简洁、更快速!腾讯云 Serverless 云函数创建流程再次升级!
  17. 粗涉Webpack
  18. Frequently asked questions in front end interview: JS garbage collection mechanism
  19. ReactDOM.render Serial rendering link (1)
  20. More concise and faster! Tencent cloud serverless cloud function creation process upgrade again!
  21. 更简洁、更快速!腾讯云 Serverless 云函数创建流程再次升级!
  22. About webpack
  23. More concise and faster! Tencent cloud serverless cloud function creation process upgrade again!
  24. 详解vue静态资源打包中的坑与解决方案
  25. 一篇搞懂TCP、HTTP、Socket、Socket连接池
  26. 字节跳动2021前端技术岗发布+最新内部面试题
  27. Detailed explanation of Vue static resource packaging and Solutions
  28. Understanding TCP, HTTP, socket, socket connection pool
  29. 2008-2021 front end technical post release + latest internal interview questions
  30. 4. Vue基本指令
  31. 4. Vue basic instruction
  32. Java 发起 http 请求
  33. Java initiates HTTP request
  34. 网站由http升级为https图文教程
  35. Upgrade the website from HTTP to HTTPS
  36. 更简洁、更快速!腾讯云 Serverless 云函数创建流程再次升级!
  37. More concise and faster! Tencent cloud serverless cloud function creation process upgrade again!
  38. 混合开发入门 Vue结合Android/iOS开发仿京东项目App
  39. Hybrid development entry Vue combined with Android / IOS to develop app imitating Jingdong project
  40. 无缝对接 Tableau,这家月活跃用户 5000+ 的大型银行如何实现自助式分析?
  41. Are airpods still the strongest? Horizontal evaluation of 4 true wireless headphones
  42. Seamless connection with tableau, how can this large bank with 5000 + active users realize self-service analysis?
  43. react-native版文字跑马灯
  44. React native text running lantern
  45. Java、JavaScript、C、C++、PHP、Python都是用来开发什么?
  46. What are Java, JavaScript, C, C + +, PHP and python used to develop?
  47. this.byId(SupplierForm).bindElement in SAP UI5
  48. SAP UI5 JavaScript文件的lazy load - 懒加载
  49. this.byId (SupplierForm).bindElement in SAP UI5
  50. Lazy load lazy load of SAP ui5 JavaScript files
  51. "Gnome 3" - interface elements, desktop components, part names (learning notes) @ 20210223
  52. How to connect the ground gas to the micro front end?
  53. How to transform single / micro service application into serverless application
  54. 在 2021 年你需要掌握的 7 种关于 JavaScript 的数组方法
  55. Seven array methods for JavaScript you need to master in 2021
  56. 在 2021 年你需要掌握的 7 种关于 JavaScript 的数组方法
  57. Seven array methods for JavaScript you need to master in 2021
  58. 在 2021 年你需要掌握的 7 种关于 JavaScript 的数组方法
  59. Seven array methods for JavaScript you need to master in 2021
  60. RxHttp - 轻量级、可扩展、易使用、完美兼容MVVM、MVC架构的网络封装类库