Anything that increases efficiency and reduces overhead (network, data transfer, framework)

Memory management

Memory: Consists of read and write units, representing a piece of memory space that can be manipulated

Management: the artificial manipulation of the application, use and release of a space

Memory management: developers actively claim space, use space, free space

Memory management in js
Name = 'lg' // Free space obj = nullCopy the code
Garbage in javascript
  • Js memory management is automatic
  • Objects are garbage when they are not referenced
  • Objects that cannot be accessed from up are garbage
Reachable objects in js
  • Accessible objects are reachable objects (references, scope chains)
  • The criterion of reachability is whether it can be found from the root
  • Roots in JS can be thought of as global variable objects

Find the garbage and let the JS engine free and recycle the space

GC algorithm

GC: Garbage collection mechanism

  • An object in a program that is no longer needed
  • An object in a program that can no longer be accessed

What is the GC algorithm

  • GC is the mechanism by which the garbage collector does the specific work
  • The content of the work is to find the garbage release space, recycling space
  • An algorithm is a set of rules that lookup and recycle follow at work
Implementation principle of reference counting algorithm

Core idea: Set the number of references. Checks whether the current number of references is 0

Reference counter:

Modify the reference number when the reference relationship changes

Reclaim immediately if the reference number is 0

const user1 = {age: 11}
const user2 = {age: 12}
const user3 = {age: 13}

const namelist = [user1.age, user2.age, user3.age]

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

Advantages: Recycle garbage immediately when it is found, minimizing program pauses

Disadvantages: Unable to recycle referenced objects, time overhead

function fn() {
    const obj1 = {}
    const obj2 = {}
    obj1.name = obj2
    obj2.name = obj1
    return 'zxt'
}

fn()
Copy the code
Mark clearing algorithm

Core idea: mark and clear two stages to complete

Walk through all the objects looking for the mark active object

Iterate over all objects to remove unmarked objects

Reclaim space

Advantages: Solve the problem that circular references cannot be recycled

Disadvantages: generate space fragmentation problems, can not maximize space use

Tag sorting algorithm

Think of it as an enhancement to tag clearing

The operation of the tag phase is the same as that of tag clearing

The cleanup phase starts with a cleanup, moving the object

Advantages: Reduced fragmentation space

Disadvantages: Garbage objects are not immediately recycled

V8

Is a mainstream JS execution engine

Just-in-time compilation

V8 memory limit

Garbage Collection strategy
  • Adopt the idea of generational recycling

  • Memory is divided into new generation, old generation

  • Different algorithms are used for different objects

    V8 commonly used GC algorithm: generational recycling, space replication, mark clearing, mark collation, mark enhancement

Recycle new generation objects
  • V8 memory space is split in two

  • Little space to store the new generation object (32 m | 16 m)

  • The Cenozoic era refers to objects that have a short life span

    implementation

    • The recycling process adopts replication algorithm + label finishing
    • The new generation of memory is divided into two equal size Spaces
    • The use space is Form and the free space is To
    • Active objects are stored in the Form space
    • Copy the live object To To after the tag is collated
    • The Form and To swap space To complete the release

    Recovery Details

    • Promotions may occur during copying
    • Promotion is the movement of the new generation to the old generation
    • A new generation of GC still alive needs to be promoted
    • To The space usage exceeds 25%
Reclaim old generation objects
  • The old generation object is placed in the old generation area on the right

  • 64-bit OPERATING system 1.4 GB, 32-bit operating system 700 MB

  • An old generation object is an object that lives for a long time

    implementation

    • It mainly adopts the algorithm of mark clearing, mark finishing and increment mark
    • Garbage space is first collected using a tag sweep
    • Spatial optimization was carried out by label finishing

    Details of the contrast

    • The new generation of regional garbage recycling uses space exchange time
    • Old-generation area garbage collection is not suitable for replication algorithms
How do tag deltas optimize garbage collection

Performance Tool Introduction

Several ways to monitor memory

Browser task manager
Timeline Records the Timeline diagram
Heap snapshot looks for detached DOM

The separation of the DOM

  1. Interface elements live in the DOM
  2. Dom node when garbage object
  3. Separate state DOM nodes
Why frequent garbage collection
  • The application is stopped while the GC is working

  • Frequent and long GC can lead to application suspension

  • The user awareness application is stuck

    • Frequent ups and downs in Timeline
    • Frequent additions and decreases in task manager

Be careful with global variables

  • Global variables are defined in the global execution context and are at the top of any scope chain
  • The global execution context remains in the context execution stack until the program exits
  • The presence of a variable with the same name in a local scope obscures or contaminates the whole world

Caching global variables

Add additional methods through the prototype object

var fn1 = function () {
    this.foo = function () {
        console.log(1111)
    }
}
fn1 = new fn1()

var fn2 = function () {}
fn2.prototype.foo = function () {
    console.log(1111)
}
fn2 = new fn2()
Copy the code

Avoid closure traps

function foo () {
var el = dociment.getElementById('btn')
   e.onclick = function() {
       console.log(el.id)
   }
   el = null
}
foo()
Copy the code

Avoid attribute access methods

  • JS does not require attribute access methods, all attributes are externally visible
  • Using attribute access methods only adds another layer of redefinition, with no access control
function Person() {
    this.name = 'zs'
    this.age = 18
    this.getAge = function () {
        return this.age
    }
}
const p1 = new Person()
const a = p1.getAge()

function Person() {
    this.name = 'zs'
    this.age = 18
}
const p2 = new Person()
const b = p2.age
Copy the code

FOR loop optimization

var btns = dociment.querySelector('btn') for (var i = 0; i < btns.length; I ++) {console.log(I)} for (var I = 0; len = btns.length; i < len ; i++) { console.log(i) }Copy the code

Most cyclic algorithm

Var arr = new Array(1, 2, 3, 4, 5); var arr. ForEach (item => {console.log(item)}); len = arr.length; i < len ; i++) { console.log(arr[i]) } for (var i in arr) { console.log(arr[i]) }Copy the code

Document fragmentation optimization node added

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

Clone optimized node operation

for (var i = 0; i < 3; I++) {var oP = document. The createElement method (' p ') oP. InnerHTML = I document. The body. The appendChild (oP)} / / optimal var oP = document.createElement('p') for (var i = 0; i < 3; i++) { var newP = oldP.cloneNode(false) oP.innerHTML = i document.body.appendChild(oP) }Copy the code

Replace the new Object directly

var a = new Array(3)
a[0] = 1
a[1] = 2
a[2] = 3

var a = [1, 2, 3]
Copy the code