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

Huawei cloud developer community 2021-02-23 10:28:14
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 .

image

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 :

image

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 .

image

image

image

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 .

image

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 .

image

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 .

image

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 .

image

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

image

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

image

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

image

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/20210223102604896n.html

  1. How to build a high performance front end intelligent reasoning engine
  2. How to become a professional front end engineer in 2021?
  3. How to transform single / micro service application into serverless application
  4. How to transform single / micro service application into serverless application
  5. How to transform single / micro service application into serverless application
  6. How to connect the ground gas to the micro front end?
  7. How to connect the ground gas to the micro front end?
  8. How to connect the ground gas to the micro front end?
  9. Vue server rendering principle analysis and introduction
  10. Realize the correct loading of text message
  11. Building my own project scaffolding with yeoman
  12. JavaScript advanced prototype and prototype chain
  13. React background management front end system (based on open source framework development) start
  14. JS practical skills breakpoint debugging
  15. I'd like to share with you 20 super easy-to-use Chrome extension plug-ins
  16. Get page element location
  17. Use the powerful API of modern browser to record any interface in the browser and realize export, save and management
  18. Delayed code execution in flutter
  19. Reconfiguration experience of KOA middleware system
  20. Add comments to your blog
  21. Svg editor -- new path
  22. Detailed explanation of debounce and throttle of JavaScript function
  23. Anti shake and throttling and corresponding react hooks package
  24. C2m: the first CSDN article moved to MOOC script 5000 words, detailed painstaking development process, there are renderings and source code at the end of the article
  25. Front end, school recruitment, Taobao, guide
  26. [vue2 & G6] get started quickly
  27. Canvas from the beginning to the pig
  28. Take five minutes to standardize the code comments?
  29. Some thoughts on sass
  30. what?! You haven't filled in the award information yet
  31. How to get the interface + tsdoc needed by TS through swagger
  32. Binary tree
  33. Canvas drawing method in Web screenshot
  34. Front end docker image volume optimization (node + nginx / node + multi-stage construction)
  35. Become a big influence of technology? Coding pages quickly build personal blog
  36. Object and array deconstruction, spread operator, rest operator
  37. Analysis of Axios source code
  38. Two ways to delete useless code in project (Practical)
  39. Edit your picture with canvas
  40. Today's chat: 2-4 years to walk out of the resignation dilemma and comfort zone
  41. JS mechanism 3: stack, heap, garbage collection
  42. [grid compression evaluation] meshquan, meshopt, Draco
  43. Deep understanding of Vue modifier sync [Vue sync modifier example]
  44. WebView for front end engineers
  45. React form source code reading notes
  46. Deep thinking about modern package manager -- why do I recommend pnpm instead of NPM / yarn?
  47. On the sequence of event capture and event bubbling
  48. Help you build a systematic understanding of the front end scaffolding
  49. commander.js Principle analysis
  50. Common usage of nginx
  51. H5 jump to wechat app
  52. Front end algorithm interview must brush questions series [14]
  53. Thinking of cross end practice
  54. Vue server rendering principle analysis and introduction
  55. [KT] vscode plug in development example series (2)
  56. Design ideas of react and Vue framework
  57. JavaScript String.prototype.replaceAll 兼容性导致的问题
  58. JavaScript String.prototype.replaceAll Problems caused by compatibility
  59. 爱奇艺体育:体验Serverless极致扩缩容,资源利用率提升40%
  60. Iqiyi Sports: experience the ultimate expansion and contraction of serverless, and increase the utilization rate of resources by 40%