Due to the length of the js performance optimization section is written in the next chapter

Js performance excellent next :juejin.cn/post/688341…

Section TS: juejin.cn/post/688342…

Part 1: New ECMAScript features

One: ES2015-let and code block

  1. Scope: The scope in which a member can function. Before this, there were only two types of scope in ES (global scope, function scope). In ES2015, block-level scope was added.
  2. In the past, there was no independent scope, so variables in a code block could be accessed by outsiders.
  3. Var has variable declarations, let does not.

2: ES2015 – const

  1. [readonly] effects are not allowed to be modified after being declared (attribute members, such as members of objects, can be modified)

  2. Const must be copied at the same time it is declared; let does not

    // Const name = 'XJQ' name = 'x' const = a a = 'c' console.log(a) Because const obj = {} obj.age = 22 console.log(obj) // {age:22} because const does not allow to modify the memory address pointing, but can modify the attribute memberCopy the code

Three: ES2015- Array deconstruction

// const f1 = arr[0] const f2 = arr[1] const f3 = arr[2] console.log(f1, f2, // 100 200 300 //ES2015 array const [f4, f5, f6] = arr console.log(f4, f5, f6) Const [,, f7] = arr console.log(f7) = 300 //... The use of const [foo, ...rest] = arr console.log(foo) // 100 console.log(rest) // [200,300] // only one member acquires the first const [f8] = arr console.log(f8) // 100 // undefined const [f9,f10, f11, F12] = arr console.log(f12) const [f13, f14 = 400, f15 = 500, f16 = 600] = arr console.log(f13, f14, f15, f16) // 100 200 300 500Copy the code

ES2015- Deconstruction of objects

  1. Object extraction requires fetching by name, unlike array deconstruction because array elements have subscripts and order rules, whereas the members of an object have no order
  2. Conflicts can occur if the current scope has the same variable name, and the solution is to change the variable name at deconstruction time
  3. Other features are basically the same as array deconstruction

Five: ES2015- Template string

const str = console.log`hello world` // ['hello world'] const name = 'tom' const gender = true function tarFunc(strings, Name, gender){console.log(strings, name, gender) // Tagged template string can print static members ["hey,"," is a"," ", raw: Array(3)] "Tom" true } const retult = tagFunc 'key,${name} is a ${gender}' console.log(result) // This is the return value of the template stringCopy the code

Six: ES2015- String extension method

  1. Includes () — What does the string contain and return a Boolean value

  2. StratsWith () — What begins the string and returns a Boolean value

  3. EndWith () – What end of the string returns a Boolean value

    const message = “Error: foo is not defined.”

    console.log(message.stratsWith(‘Error’)) // true

    console.log(message.endWith(‘.’)) // true

    console.log(message.includes(‘foo’)) // true

Seven: ES2015- The default value of the parameter

Function foo(enable = true){console.log(enable)} foo(Copy the code

Eight: ES2015- Remaining parameters

  1. Arguments was used before, but arguments is a pseudo-array

Nine: ES2015- Expand array

const arr1 = ["f1", "f2", "f3"] const arr2 = ["f2","f3","f4","f5","f6"] console.log(... arr1) //f1 f2 f3 console.log(... arr1 , arr2) //f1 f2 f3 f2 f3 f4 f5 f6Copy the code

Ten: ES2015- Arrow functions

  1. The arrow function does not change the direction of this

Eleven: ES2015- Object literals enhanced

Const bar = 123 const obj = {foo: 123, //bar:bar, //method: Function (){}, this can also be done with the object literal method1(){console.log(' Tuen ') retuen '} // Dynamic add attribute name [math.random] : 13} // add property obj[math.random ()] = 147 console.log(obj) console.log(obj.method1())Copy the code

12: ES2015- Object extension method – object.assign

  1. Assign attributes from multiple source objects to a target object, if there are nine overrides for the same attribute
  2. Multiple object parameters can be entered, the first being the target object

13: ES2015- Object extension method – object.is

  1. Used to determine whether two values are equal
  2. === ===

ES2015- Basic syntax for proxy objects

  1. Used to listen to the reading and writing of objects
  2. More powerful and convenient than defineProperty
  3. Two parameters are supported, the first being the agent target and the second being the agent’s processing object

ES2015- Proxy object Proxy versus defineProperty

  1. Proxy is more powerful because defineProperty can only monitor reads and writes of attributes and Proxy can monitor more object operations.
  2. Proxy is a better way to monitor array objects. Previously, the most common way to defineProperty was to override the operation method of arrays.
  3. Proxy regulates the read and write of objects in a non-intrusive manner and does not need to operate on the objects themselves, whereas Object.defineProperty operates on the objects themselves.

Es2015-reflect unified object manipulation API

  1. Reflect is a static class and cannot provide new Reflect to create an instance object. It can only call static methods of the static class, such as reflect.get ().
  2. Reflect internally provides a series of low-level operations on objects
  3. The Reflect member method is the default implementation of proxy handling objects
  4. The point of existence is to provide a set of apis, there are 13 methods

17: ES2015 – promise

  1. Here before the notes sorted out, you can jump to the following chain
  2. Juejin. Cn/post / 687787…

18: es2015-class

  1. Constructor is a constructor
  2. Class has instance methods and static methods
  3. Static member –static(static method)
  4. Because static methods are mounted on classes, this method does not point to instance methods

19: Es2015-class inheritance

  1. Key words: extends
  2. The super keyword: always points to the parent class, and calling it calls the constructor of the parent class

20: ES2015-SET data structure

  1. Set internal members are not allowed to be duplicated, and values are unique
  2. The add method returns the collection object itself, so it can be called chained
  3. A common scenario is array de-duplication

21: ES2015-Map data structure

  1. The key of this object can be of any type; ordinary objects can only be strings
  2. Normal objects whose keys use other types of values are converted to strings. Maps are not
  3. The biggest difference between Map data structures and ordinary objects is that they can use keys of any type. Objects can only use strings

A completely new data structure

  1. Symbol represents unique values. Values created through Symbol are unique
  2. The main function is to add a unique attribute name to an object
  3. Global reuse of the same Symbol value can use Symbol’s static method for, the value passed to the for method is automatically converted to a string

ES2015-for… Of circulation

  1. Can be used as a unified way to traverse all data structures
  2. for… The of method can terminate the loop using the return method
  3. But looping plain objects will report an error because they do not implement an iterable interface, whereas other data classes do

Twenty-four: ES2015- Iterable interface

  1. Implementing an iterative interface is for… Of the premise
  2. All is for.. The data structures of the OF loop are all Interable

ES2015- Implementing an iterative interface

const obj = {
store: ['foo','bar','baz'],

[Symbol.iterator]: function(){
let index = 0
const self = this
return {
next : function(){
const result = {
value : self.store[index],
done : index >= self.store.length
}
index ++
return result
}
}
}
}
for (const item of obj){
console.log(item)  // foo  bar  baz
}
Copy the code

26: ES2015- Iterator pattern

  1. The meaning is to provide a unified external interface, the external need not know the internal data structure and implementation principle

27: ES2015- Generator

  1. Avoid deep nesting of callbacks in asynchronous programming
  2. The generator function automatically generates a generator object that needs to be executed by calling the next method
  3. When the yield keyword is encountered during execution, the execution of the function is paused and next is called again

ES2015- Applications of generators

  1. The most important purpose is to solve the problem of transition nesting in asynchronous programming

29: ES2015-Modules

  1. This point will be discussed in detail next time when writing engineering notes

Thirty: ES2016

  1. Includes, the previous indexOf method could not find NaN, but includes does
  2. Exponential operator

Thirty-one: ES2017

  1. Object.values is similar to ES2015 object. key, with one return value and one return key
  2. Object.entries return all the key values of an Object as an array. This method allows you to traverse normal objects without having to write iterator 9 yourself, or to convert objects to maps
  3. Object. GetOwnPropertyDescriptors can obtain the complete description of the properties in the Object
  4. String. The prototype. PadStart/String. Prototype. PadEnd – filling method two strings
  5. The function adds a comma to the argument
  6. async / await

The second part :JS performance optimization

One: Memory management

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

  2. Management: the artificial operation of the application, use and release of a space

  3. Memory management: developers actively apply for space, use space, free space

  4. Management process: application – Use – Release

  5. Memory management in JavaScript – Apply memory management – use memory space – free memory space

    Function fn(){arrList = [] arrList[100000] = ‘XJQ’} fn(){arrList = [] arrList[100000] = ‘XJQ’} fn()

    // apply const obj = {} // use obj. Name = ‘XJQ’ // release obj = null

Two: garbage collection in JavaScript

  1. Memory management in JavaScript is active

  2. Objects that are no longer referenced are garbage

  3. Objects that cannot be accessed from the root are garbage

  4. Accessible understanding

  5. In a scope, any object that provides a root to which a path can be traced is reachable

  6. Accessible objects are reachable objects (references, scopes)

  7. The criterion of reachability is whether it can be found from the root

  8. Javascript roots can be understood as global variable references

    //{} object space is referenced by obj and can be accessed, so it is reachable let obj = {name: ‘XJQ ‘} // The object is reachable even if obj=null

    // If o1 and prve are not referencing obj1, Function objGroup(obj1, Obj2){// Next of obj1 references obj2. Next = obj2 // prve of obj references obj1. Prve = obj1 return {//o1 references o1: Obj2 o2: obj2}}

    Let obj = objGroup({name: ‘obj1’}, {name: ‘obj2’})

Three: GC algorithm introduction

  1. GC is short for garbage collection mechanism
  2. The GC finds garbage in memory and frees and reclaims space
  3. Objects in the program that are no longer needed are garbage in the GC
  4. Objects in the program that are no longer accessible are garbage in the GC
  5. GC is a mechanism where the garbage collector does the specific work
  6. The content of the job is to find garbage release space, recycling space
  7. The GC algorithm is the rules that lookup and recycle follow at work
  8. A common GC algorithm – reference counting
  9. A common GC algorithm – tag clearing
  10. Common GC algorithm – tag collation
  11. Common GC algorithms — Generational collection (common in V8)
Function func1(){function func1(){name: Function func2(){const name = 'XJQ'; function func2(){const name = 'XJQ'; Return '${name}'}Copy the code

Four: implementation principle of reference counting algorithm

  1. Core idea: set the number of references, determine whether the current number of references is 0, 0-GC starts to work, reclaim the content of the object, free space

  2. Reference counter

  3. Modify the reference number when the reference relationship changes (for example, in an object space, if there is a variable pointing to, subtract one if there is no reference)

  4. Recycle immediately when the reference number is zero

    const user1 = { age: 11} const user2 = { age: 22} const user3 = { age: 33}

    Const nameList = [user1.age, user2.age, user3.age] const nameList = [user1.age, user2.age, user3.age]

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

Four: advantages and disadvantages of reference counting algorithm

  1. Advantages: Found garbage immediately recycling

  2. Advantages: Minimize program pause (memory full will · pause)

  3. Disadvantages: Unable to recycle objects referenced in a loop

  4. Disadvantages: Event overhead (because counting needs to be maintained counting. Need to monitor number changes at all times)

    Function fn(){const obj1 = {} const obj2 = {}

    Obj1.name = obj2 obj2.name = obj1} fn()

Five: the realization principle of mark clearing algorithm

  1. Core idea: mark and clear two stages to complete
  2. Walk through all the objects looking for the mark active object
  3. Iterate over all objects to remove unmarked objects (while erasing previous marks)
  4. Reclaim the corresponding space (the reclaimed space will be put on the free list for the convenience of applying for space continuously in the future)

Six: Advantages and disadvantages of reference counting algorithm

  1. Advantages: Recycled objects can be recycled
  2. Disadvantages: Storage space fragmentation of the free list, because the space freed by the previous reclamation is not continuous, subsequent memory application. Maybe the space is not the right size

Seven: the realization principle of the tag collation algorithm

  1. The tag here can be seen as an enhancement to tag clearing
  2. The operation of the tag phase is the same as that of tag clearing
  3. The cleanup phase starts with a cleanup, moving objects (to achieve spatial continuity)

Eight: Get to know V8

  1. V8 is a mainstream javascript execution engine
  2. V8 uses just-in-time compilation (converting source code directly into currently executable machine code)
  3. V8 memory limit (64-bit not exceeding 1.5G, 32-bit not exceeding 800M)

Nine: V8 garbage collection strategy

  1. Adopt the idea of generational recycling
  2. Memory is divided into new generation and old generation
  3. Different algorithms are used for different objects
  4. A common GC algorithm in V8 – generational collection
  5. A common GC algorithm in V8 – spatial replication
  6. A common GC algorithm in V8 – tag clearing
  7. A common GC algorithm in V8 – tag collation
  8. A common GC algorithm in V8 – mark increments

Ten: v8 how to recycle the new generation of objects

V8 memory allocation

  1. V8 space split in two
  2. Little space to store the new generation object (64 – bit operating system is 32 m 16 m | 32-bit operating system)
  3. Cenozoic refers to objects that have a short life span

New generation object recovery implementation

  1. The recycling process adopts space copy + label finishing
  2. The new generation memory is divided into two equally large Spaces
  3. The used space is in the From state, and the free space is in the To state
  4. Live objects are stored in the From space (actions are triggered when the space reaches a certain limit)
  5. Copy live objects To To (make live objects contiguous for convenience without fragmentation later)
  6. Free From space (From To space)

Detail description

  1. – Promotion is possible during copying (the space that an object points to is found during copying, and also occurs in old generation)
  2. Promotion is the movement of the new generation to the old generation
  3. A new generation of GC who is still alive needs to be promoted (trigger promotion move to old generation)
  4. To space usage exceeds 25% (triggers promotion move To old generation)

How does V8 recycle old generation objects

Old generation object description

  1. Old generation objects are stored in the old generation area on the right
  2. 64-bit OPERATING system 1.4 GB, 32-bit operating system 700 MB
  3. A legacy object is an object that has a long lifetime (globally stored variables, closures, etc.)

Old generation object recycling implementation

  1. The main use of mark clearing, mark finishing, incremental mark
  2. Garbage space is first collected using a tag sweep
  3. Space optimization using mark arrangement (mark arrangement will be carried out when there is insufficient space in the new generation movement)
  4. Efficiency optimization with incremental marking (i.e. a whole garbage collection is broken up into smaller sections and combined to complete the garbage collection)

Details of the contrast

  1. New generation of regional garbage recycling use space for time (due to the small space)
  2. Old age area garbage collection is not suitable for the spatial replication algorithm (because of the large space, using the spatial replication algorithm will lead to a large waste of space, and the old age stores more data)

Xii: Introduction to Perfromance

Why use Performance

  1. The purpose of GC is to achieve a virtuous cycle of memory space
  2. The cornerstone of a virtuous cycle is rational use
  3. Keep an eye on it to see if it makes sense
  4. Performance Provides multiple monitoring modes
  5. Provides Performance time monitoring memory

Performance Procedure

  1. Open Google Chrome and type in the target url
  2. Go to the Developer panel and select Performance
  3. Enable the recording function and access the page
  4. Perform user action and stop recording after a certain period of time
  5. You need to select the memory option to display the memory graph and analyze the memory information on the page

Thirteen: the embodiment of memory problems

  1. Page lazy loading or inheritance pausing (except in network environment) (persistent memory collection) (frequent garbage collection)
  2. Persistent poor page performance (memory bloat)
  3. Page performance deteriorates over time (memory leak)

Several ways to monitor memory

Criteria for defining memory problems

  1. Memory leak: Memory usage continues to rise
  2. Memory bloat: Performance issues on most devices
  3. Frequent garbage collection: Analysis by memory analysis chart (continuous increase, no downward trend)

Several ways to monitor memory

  1. Browser task manager
  2. Timeline Records the Timeline diagram
  3. Heap snapshot looks for detached DOM

Fifteen: Task manager monitors memory

  1. How to open it: Click on the top right of Chrome – more tools – Task Manager
  2. Shortcut key — Shift + ESC
  3. Right click on the target to enable JavaScript memory
  4. Memory is the amount of memory that a BOM node occupies — if it is increasing, it means that a new DOM is being created
  5. JavaScript memory refers to the JS heap (see values in parentheses)

Xvi: Memory for Timeline records

  1. F12 Open developer tools
  2. Select Performance– Start recording — Open the page for operation — stop recording — check the memory option and view the memory direction diagram

Heap snapshot lookup separate DOM

What is DOM separation

  1. Interface elements live in the DOM tree
  2. The DOM node of the garbage object (if the node is separated from the current DOM tree, but the JS code still references it)
  3. Separate state DOM nodes (if the node is separated from the current DOM tree, but the JS code still references it)
  4. These are memory leaks

Use of Snapshots

  1. Open Google Browser, open developer Tools, select Memory, and check read a snapshot
  2. The interface is complete. Click Take Snapshot
  3. Search Detached

Determine if frequent GC exists

  1. The application is stopped while the GC is working
  2. Frequent and long GC can lead to application suspension
  3. The user awareness application is stuck
  4. Determine frequent garbage collection — Frequent ups and downs in Timeline
  5. Identify frequent garbage collection – frequent additions and deletions of data in task manager