This is the 29th day of my participation in the August Wenwen Challenge.More challenges in August

Performance optimization

  • Performance optimization:

    • Performance optimization is inevitable
    • Any operation that improves operating efficiency and reduces operating costs is a performance optimization
  • Understand optimizations on the JavaScript language itself

    • Memory management
    • Garbage collection mechanism
    • To write efficient JavaScript code
  • There are several dimensions to understand the performance optimization of JavaScript itself

    • Memory management
    • Garbage collection and GC algorithm
    • V8 engine garbage collection
    • The Performance tool displays monitored memory
    • Optimized code example
  • Reduce memory problem code

Introduction to Memory Management

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

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

Memory management: Developers apply space to memory, use space, and release space

Management process: apply – use – release

  • Memory management in JavaScript

    Find the garbage and let the JS engine recycle it

Because JavaScript language itself does not provide relevant memory space application, use memory space, free memory space API, so JS can not be as ACTIVE as C/C ++ to do memory related processing.

JavaScript in the garbage

  • Memory management is automatic in JavaScript

  • Objects are garbage when they are no longer referenced

  • Objects that cannot petition from the root are asked about garbage

Reachable objects in JavaScript

  • Accessible objects are reachable objects (references, scope chains)

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

  • The root in JavaScript can be understood as a global variable object (global execution context)

GC definitions and functions

  • GC is short for garbage collection mechanism

    • What is the garbage in the GC?

      1. Objects that are no longer needed in a program

        function fn() {
          name = 'lg'
          return name
        }
        Copy the code
      2. An object in a program that can no longer be accessed

        function fn() {
        	const name = 'lg'
          return name
        }
        Copy the code
  • The GC finds garbage in memory and frees and reclaims space

What is the GC algorithm

  • Gc is a mechanism where the garbage collector performs specific actions
  • The content of the work is to find the garbage release space, recycling space
  • An algorithm is the work followed by lookup and recycle at work

How to find space, how to release space, how to allocate space in the process of recycling

Common Gc algorithms

  • Reference counting
  • Mark clear
  • Tag cleanup (similar to tag cleanup, but with a different mechanism for recycling)
  • Generational recycling

Implementation of reference counting algorithm

  • The main idea: The reference counter maintains the number of references to the live object, determines whether the current number of references is 0, and if it is 0, determines that it is garbage, and then the GC starts to collect garbage.
  • Modify the reference number when the reference relationship changes
  • Reclaim immediately if the reference number is 0.

Advantages of reference counting algorithms

  • Recycle rubbish as soon as it is found
  • Minimize program pauses

Disadvantages of the reference counting algorithm

  • An object referenced by a reference loop cannot be reclaimed

  • Time is expensive and speed is relatively slow

    Object for a circular reference

    function fn() {
      const obj1 = {}
      const obj2 = {}
      obj1.name = obj2
      obj2.name = obj1
      
      return 'aa'
    }
    fn()
    Copy the code

The realization principle of tag clearing algorithm

  • Core idea: Divide the whole garbage collection into two phases
    • Traverse all objects to find objects marked active (reachable)
    • Iterate over all objects to remove unmarked objects, and remove unmarked objects
    • Reclaim space

Advantages and disadvantages of tag clearing algorithms

  • Object recycling is resolved
  • But with the problem of space fragmentation,
    • Space fragmentation: Since the garbage objects we currently recycle are discontinuous in the address itself, they are scattered in various locations of the space after recycling. If the memory space is large or small, the memory space will not be fully utilized next time.

Principle of tag collation algorithm

  • Tag cleanup can be seen as an enhancement to tag cleanup
  • The operation of the tag phase is the same as that of tag clearing
  • The cleanup phase starts with a cleanup, moving objects so that they have continuity in their addresses.
Know the v8
  • V8 is a mainstream JavaScript execution engine
  • V8 uses just-in-time compilation and directly compiles the source code to machine code for direct execution.
  • V8 memory limit 64-bit 1.5G 32-bit 800M

V8 garbage collection strategy

In the process of using the program, we will use a lot of data, there are raw data and reference data, the original data is controlled by the language itself, and reference data is in the heap, so it needs memory management

  • Adopt the idea of generational recycling
  • Memory is divided into new generation objects and old generation objects
  • Different algorithms are used for objects of different generations (new generation, old generation), which is more efficient.

Common GC algorithms in V8

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

V8 Memory Allocation

  • V8 memory space is split in two
  • Small space for storing new generation objects (32M | 16M)
  • 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 is divided into 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

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 space usage exceeds 25%

Old generation object recycling implementation

  • Old generation objects are stored in the old generation area on the right
  • 64-bit 1.4g 32-bit 700M
  • An old generation object is an object that has a long lifetime (closure, global)

Old age object recycling implementation

  • It mainly adopts the algorithm of mark clearing, mark finishing and increment mark
  • The garbage space is collected first with the flag cleared
  • Spatial optimization using marker arrangement (old generation object moving to new generation object)
  • 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, and splitting memory into two is wasteful

V8 summary:

  • V8 was designed for browsers and is a mainstream JavaScript execution engine
  • V8 memory upper limit
  • V8 adopts the idea of generational recycling to realize garbage collection
  • V8 memory is divided into new generation and old generation
  • V8 common GC algorithm for garbage collection
Performance
  • The purpose of GC is to achieve a virtuous cycle of memory space
  • The cornerstone of a virtuous cycle is rational use
  • Keep an eye on it to see if it makes sense
  • Performance Provides multiple monitoring modes

Performance Procedure

  • Open your browser and enter the destination url
  • Go to the Developer tools panel and select Performance
  • Enable the recording function and access the specific page
  • Perform user action and stop recording after a certain period of time
  • Analyze the memory information recorded on the page.

External manifestation of memory problems (under normal network conditions)

  • Pages that load lazily or pause frequently (GC occurs frequently)
  • Persistent poor page performance (memory bloat, requiring more memory than the device can provide for a better experience)
  • Page performance deteriorates over time (memory leaks)

Criteria for defining memory problems

  • Memory leak: Memory usage continues to rise
  • Memory bloat: Performance issues on most devices
  • Frequent garbage collection: Analyzed by memory variation graph

Several ways to monitor memory

  • Browser task manager
  • Timeline Records the Timeline diagram
  • Heap snapshot looks for detached DOM
  • Determine if there is frequent garbage collection

What is dom separation

The working principle of the heap snapshot function is as follows: Saves the JS heap snapshot.

  • Interface elements live in the DOM tree
    • The DOM phase when an object is garbage
      • The DOM node is removed from the DOM tree and no reference is made to it in the JS code
    • Separate state DOM nodes
      • The DOM node is detached from the DOM tree, and the JS code has no reference to it.
Code optimization
  • Be careful with global variables

    • Make the global as local as possible
    • Global variables that cannot be avoided in use are cached locally
      • For example, cache document
  • Adding additional methods through prototypes provides faster execution

  • Avoid closure traps

    • Closures can easily leak memory when used improperly
function foo() {
  var name = 'lg'
  return function () {
		console.log(name)
  }
}
var a = foo()
a()
// Closure characteristics
// 1. For the function foo that generated the closure, its outer has a reference to its inner
// 2. In the outer scope (a function) can access the data in the inner scope (foo function) (foo function name)
Copy the code
  • Avoid property access methods

    Object orientation in JavaScript

    • 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.name = 'icoder'
        this.age = 18 // If privatized
        this.getAge = function() {
          return this.age
      	}
      }
      new Person().getAge() // slower
      new Person().age  // faster
      Copy the code
  • Document fragmentation optimization node added

    • The addition of nodes inevitably involves backflow and redraw

      // Define the document shard container
      const fragEle = document.createDocumentFragment()
      for(var i =0; i<10; i++) {var op = document.createElement('p')
        op.innerHTML = i
        fragEle.appendChild(op)
      }
      // Want to add a document fragment container to the body
      document.body.appendChild(op)
      Copy the code