The core is: JS language optimization

  • Memory management
  • Garbage collection &GC algorithm
  • V8 engine garbage collection
  • The performance monitor
  • Code optimization examples

First, JS memory management

Memory: Composed of read and write units, representing a piece of operable space

Management: To manage the application, use, and release of a space

Memory management: developers actively apply for space, use space, release space

Management process: application – Use – Release

Memory management in js:

  • To apply forlet obj = {}
  • useobj.name = '1'
  • The release ofobj = null

Garbage collection in JS

  • Js memory management is automatic
  • Objects are garbage when they are no longer referenced
  • Objects are garbage when they cannot be accessed from the root
  • Js has its own garbage collection mechanism

Reachable objects in JS

  • Objects that can be accessed are reachable objects
  • Reachable criteria is whether the trigger can be found from the root
  • Roots in JS can be understood as global variable objects

GC algorithm

  • GC is short for garbage collection mechanism
  • The GC finds garbage in memory and frees and reclaims space
  • Garbage: garbage that a program no longer needs && objects that can no longer be accessed by a program

GC is a mechanism where the garbage collector does its job by finding the garbage free space, and the collection space algorithm is the rules that are followed for finding and collecting at work

Common GC algorithms

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

Second, reference counting algorithm

Set the number of references to check whether the current number of references is 0

Advantages and disadvantages of reference counting algorithms

  • Garbage objects can be collected in a timely manner
  • Minimize program lag time
  • Object referenced by loop cannot be recycled
  • High resource consumption
Function fn1(){const obj1 = {} const obj2 = {} obj1.name = obj2 obj2.name = obj1 return '11'} fn1() Obj2. Name is a reference to obj1. // This is a circular reference to objectsCopy the code

Mark clearing algorithm

The whole garbage collection is divided into two stages: mark and remove

Go through all the objects, find the mark active objects go through all the objects remove the unmarked objects and reclaim the corresponding space

The advantages and disadvantages

  • Can solve the recycling operation of object circular reference
  • Space fragmentation. Garbage objects currently collected are not contiguous in address and cannot be used to maximize space usage.
  • Garbage objects cannot be collected immediately
  • The program stops working during collection

4. Mark sorting algorithm

Tag cleanup can be seen as an enhancement to tag cleanup

  • The marking phase operates the same as the marking sweep
  • The cleanup phase starts with a cleanup to move the position of the object so that it is contiguous on the address.

The advantages and disadvantages

  • Reduce space fragmentation
  • Garbage objects are not collected immediately

V8 engine

  • V8 is the mainstream JS execution engine
  • V8 uses just-in-time compilation
  • V8 memory limit (up to 1.5GB for 64-bit and 800M for 32-bit OS)

1. V8 garbage collection strategy

  • Use generational recycling
  • Memory is divided into new generation and old generation
  • Different algorithms are used for different objects

2. GC algorithm commonly used in V8

  • Generational recycling
  • Space to copy
  • Mark clear
  • Tag to sort out
  • Mark the incremental

3. V8 recycling new generation objects

Memory allocation

  • V8 memory space is split in two
  • Little space to store the new generation object (32 m | 16 m (32 bit operating system))
  • Cenozoic refers to objects that have a short life span

New generation object recovery implementation

  • The recycling process adopts replication algorithm + label finishing
  • The new generation of memory distinguishes between two equal-size Spaces
  • The used space is From, and the free space is To
  • Live objects are stored in the From space
  • Copy the live object To To after the tag is collated
  • The space exchanged between From and To is released

Promotion may occur in the copying process. Promotion is To move the new generation object To the old generation. The new generation that is still alive needs To be promoted To the space utilization rate of more than 25%, and store the active object To the old generation

Old generation object recycling implementation

  • Old age objects are stored in the old age area on the right
  • It is 1.4 GB for 64-bit operating systems and 700 MB for 32-bit operating systems
  • An old generation object is an object that lives for a long time
  • As long as the use of mark clearing, mark finishing, incremental marking algorithm
  • Garbage space collection is completed first with a tag sweep
  • Spatial optimization was carried out by label finishing
  • Incremental marking is used for efficiency optimization

Details of the contrast

  • New generation of regional garbage recycling use space for time
  • Old-generation area garbage collection is not suitable for replication algorithms

V8 summary

V8 is a mainstream JS execution engine V8 memory set upper limit V8 based on the idea of generational garbage collection V8 memory is divided into new generation and old generation V8 garbage collection common GC algorithm

Sixth, the Performance

The purpose of GC is to achieve a virtuous cycle of memory space. The foundation of the virtuous cycle is rational use

1. External manifestations of memory problems

  • Pages are frequently paused with lazy loading activity (frequent GC operations)
  • Persistent poor page performance (memory bloat)
  • Page hungry performance gets worse over time (memory leak)

2. Way of memory monitoring

  • Memory leak: Memory usage continues to rise
  • Memory bloat: Performance issues on most devices
  • Frequent garbage collection: Analyzed by memory variation graph
  • Browser task manager
  • TimeLine Records the TimeLine diagram
  • Split DOM for snapshot lookup
  • Determine if there is frequent garbage collection

3. Timeline record memory

4. Split DOM for snapshot lookup

What is DOM separation

  • Interface elements live in the DOM tree
  • DOM node when garbage object
  • Separate state DOM nodes

Memory –> Snapshot –> DETA

5. Determine whether frequent GC exists

why?

  • The program stops when GC is running
  • Frequent and long GC can lead to application suspension
  • Users feel that the lag phenomenon is serious in use
  • Frequent ups and downs in Timeline
  • Frequent data increases and decreases in task manager

5. Code optimization

Use benchmark.js basedjsperf.com/Perform an online code line inspection

1. Use of global variables

  • Global variables are defined globally, at the top of all scope chains, and lookups require a certain amount of time, reducing the efficiency of code execution
  • The global execution context is always present in the execution stack, and GC work is not collected as garbage objects, consuming too much memory
  • A variable with the same name in a scope can obscure or pollute the whole world

2. Cache global variables

let obj = document
obj.getElementById('id')

Copy the code

Add additional methods through the prototype object

4. Avoid closure traps

Characteristics of closures

  • The outside has a reference to the inside
  • Access data from the “inner” scope in the “outer” scope
function foo(){
    var name = 'lg'
    function fn(){
        console.log(name)
    }
    return fn 
}
var a = foo()
a()
Copy the code

Closures are prone to memory leaks when used improperly

<button id="btn">add</button> <script> function foo(){ var el = document.getElementById('btn') el.onclick = function(){ Console.log (el.id)} el = null// If this line is not added, when HTML removes this element, the BTN element will still be referenced and will not be cleared by garbage collection, causing a memory leak} foo() </script>Copy the code

Avoid attribute access methods

  • JS does not require access methods for properties; all properties are externally visible
  • Using attribute access methods only adds another layer of redefinition without access control
function Person(){
    this.age = 'ii'
    this.age = 18
    this.getAge = function(){
        return this.age
    }
}
const p1 = new Person()
const a = p1.getAge()


const p2 = new Person()
const b = p1.age
Copy the code

6, For loop optimization

const aBtns = documwnt.getElementsByClass('btn');
for(vavr i = 0; i < aBtns.length; i++){
    console.log(i)
}
for(var i = 0, len = aBtns.length; i<len; i++){
    console.log(i)
}
Copy the code

Most cyclic scheme

Var arrList new Array(1,2,3,4,5) arrlist. forEach(function(item){console.log(item)}) for(var I = 0,len=arrList; i<len; i++){ console.log(arrList[i]) } for(var i in arrList){ console.log(arrList[i]) }Copy the code

7. Document fragmentation optimization node is added

const fragEle = document.createDocumentFragment()
for(var i = 0; i<10; i++){
    var oP = document.createElement('p')
    oP.innerHTML=i
    frageEle.appendChild(oP)
}
document.body.appendChild(fragEle)
Copy the code

8. Clone method to add nodes

9. Replace new Object directly

Var a = [1,2,3] var a1 = new Array(3) a1[0]=1 a1[1]=2 a1[2]=3Copy the code

JSBench

Js execution in the jsbench. Me stack

let a = 10
function foo(b){
    let a = 2
    function baz(c){
        console.log(a+b+c)
    }
    return baz
}
let fn = foo(2)
fn(3)
Copy the code

Reduce the level of judgment

Function do(part,chapter){const parts = ['es2016',' vue','react'] if(part){if(parts.includes(part) { Console. log('es2016',6) if(chapter>5){console.log('es2016',6) else{console.log('es2016',6); Function do(part,chapter){const parts = ['es2016',' vue','react'] if(! Part){console.log(" Please confirm module information ") return} if(! Parts.includes (part)) return console.log(chapter>5){console.log(chapter>5)}}Copy the code

Reduce the scope chain lookup level