Introduction: Why does code need to be optimized?

  • As Web applications become richer and richer, user experience becomes more and more important, and front-end performance becomes more and more important
  • Which type of JavaScript code has higher performance for the same results
  • Behind high performance is fast data access and excellent memory management

JavaScript 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 mainly apply for space, use space, release space
  • Management process: application – Use – Release

Garbage collection in JavaScript:

  • Memory management is automatic in JavaScript
  • Objects are considered garbage when they are no longer referenced
  • Objects that cannot be accessed from the root are garbage

Reachable objects in JavaScript:

  • Objects that can be accessed are reachable objects
  • The criterion of reachability is whether it can be found from the root
  • Roots in JavaScript can be thought of as global variable objects

GC algorithm introduction:

  • Definition and function of GC: Short for GC garbage collection mechanism; The GC finds garbage in memory and frees and reclaims space
  • Garbage in the GC: objects that are no longer needed in the program, objects that can no longer be accessed in the program
  • GC algorithm:
    • GC is a mechanism by which garbage collectors do 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

Common GC algorithms:

Reference count:
  • Core idea: set the number of references, judge whether the current number of references is 0, reference counter, reference relationship changes to modify the reference number, reference number is 0 immediately recycle;

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

  • Disadvantages: Unable to recycle objects referenced in a loop; Time consumption; High resource consumption;

Mark clearance:
  • Core idea: divide mark and clear two stages to complete, traverse all object mark active object, traverse all object mark clear unmarked object, reclaim corresponding space;

  • Advantages: Recycle referenced objects

  • Disadvantages: Unable to recycle garbage objects immediately, space fragmentation (reclaimed space is not contiguous)

Tag to sort out
  • Core idea: Mark collation can be seen as the enhancement of mark clearing. The operation in the mark stage is consistent with that in the mark clearing stage, the collation will be performed first, the position of the object will be moved, and then the clearing and recycling will be carried out

  • Advantages: Reduced fragmentation space

  • Disadvantages: Not immediately recyclable

Generation collection: Memory is divided into new generation and old generation. Different algorithms are used for different objects. For details, see V8 garbage collection mechanism

On the V8:

Know the V8:

  • A mainstream JavaScript execution engine
  • V8 uses just-in-time compilation (fast)
  • V8 memory limit (1.5G for 64-bit and 800M for 32-bit)

V8 garbage collection strategy:

  • The idea of generation recycling is adopted: memory is divided into new generation and old generation, and different algorithms are used for different objects

  • GC algorithms commonly used in V8 include generation collection, space replication, mark clearing, mark collation and mark increment

  • V8 How to recycle new generation objects: New generation refers to objects that have a short lifespan.

    • Memory allocation: V8 memory is divided into two parts, and small space is used to store new generation objects (32M/16M).
    • New generation object recycling implementation: replication algorithm + mark collation => New generation memory is divided into two equal size memory space, using space From, free space To => Active objects are stored in From space => After mark collation, active objects are copied To To => From and To exchange space To complete release
    • New generation objects that are still alive in a round of GC need To be promoted. To space usage exceeds 25%
  • How does V8 reclaim old objects: old objects are old objects

    • The old generation of object recycling implementation: mainly adopts the tag clearing, tag finishing, incremental tag algorithm; Firstly, the garbage space was recovered by mark clearing, spatial optimization was carried out by mark arrangement, and efficiency was optimized by incremental mark. (Mark increments: Since garbage collection blocks JS code execution, the collection mechanism breaks up the task for operation)
  • Comparison of new generation object and old generation object recycling details:

    • New generation of regional garbage recycling space for time (small space, large time improvement)
    • Old generation garbage collection is not suitable for replication algorithm (old generation objects have large data and large space)

Performance Tool Introduction:

Why “Performance”?

  • Purpose of GC: to achieve a virtuous cycle of memory space (rational allocation of space)
  • Performance provides multiple monitoring methods to determine proper space usage. In this case, Performance can monitor memory all the time

Memory problems:

  • Lazy loading/frequent pauses (frequent garbage collection)
  • Persistent poor performance (memory bloat => requested memory size exceeds the size provided by memory itself)
  • Performance gets worse over time (memory leak)

Criteria for defining memory problems:

  • Memory leak: Memory usage continues to rise (no falling nodes)
  • Memory bloat: The current application itself needs a large amount of memory, perhaps hardware, programs, or devices, to run tests on different devices for optimal results
  • 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

Determine if frequent GC exists:

  • The application is stopped while the GC is working
  • Frequent and long GC can lead to application suspension
  • The user awareness application is stuck

Specific operations of code optimization:

  • Use global variables with caution. Global variables continue to occupy memory. In the case of clear data scope, try to use local variables to reduce the consumption of global search time
  • Add methods by Stereotype: Add methods required by instance objects to a stereotype object
  • Avoid closure traps: Closures can easily leak memory when used incorrectly
  • Avoid attribute access methods
  • Using the optimal loop: for loop optimization (Example 1)
/ / case 1:
var arrList = []
arrList[10000] = 'icoder'
for (var i = 0; i < arrList.length; i++) {
  console.log(arrList[i])
}
// Replace the above method with the following method to reduce the js operation process
for (var i = arrList.length; i; i--) {
  console.log(arrList[i])
}

// Example 2: forEach ()
var arrList = new Array(1.2.3.4.5)

arrList.forEach(function(item) {
  console.log(item)
})

for (var i = arrList.length; i; i--) {
  console.log(arrList[i])
}

for (var i in arrList) {
  console.log(arrList[i])
}
Copy the code
  • Node addition optimization: The fixed nodes to be searched are defined in advance so that they do not have to be searched every time in the loop
// Before optimization:
for (var i = 0; i < 10; i++) {
	var oP = document.createElement('p')
	oP.innerHTML = i
	document.body.appendChild(oP)
}

// After optimization:
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 operations: You don’t have to create the DOM every time you clone
// Before optimization:
for (var i = 0; i < 3; i++) {
  var oP = document.createElement('p')
  oP.innerHTML = i 
  document.body.appendChild(oP)
}

// After optimization:
var oldP = document.getElementById('box1')
for (var i = 0; i < 3; i++) {
  var newP = oldP.cloneNode(false)
  newP.innerHTML = i 
  document.body.appendChild(newP)
}
Copy the code
  • Direct Object replacement operations: Use literal definitions
  • Reduce the level of judgment:
    • Use switch-case judgment when enumeration values are explicit
    • Avoid multiple layers of nesting, fixed conditional results to judge return in advance
  • Reduce the hierarchy of scope-chain look-ups: Define variables inside the scope-chain, using const, let-assisted variables, and minimizing var
  • Reduce the number of data reads: cache data (memory consumption)
  • Literals vs. constructors: Literals perform better than constructors (no difference in reference types)
  • Reduce the number of declarations and statements: Return data that is not used every time without caching
  • Lazy functions vs. Performance: Use lazy functions to improve performance
  • Using event delegate: using JS event bubble mechanism, the original need to bind on the child element of the response event delegate to the parent element, the parent element to complete the event monitoring, reduce event child element event registration.

Conclusion: all the above content is recorded by hand when learning, no copy and paste, all original, I hope you can bring harvest to your friends, if there are mistakes or questions welcome to leave a message, thank you for reading!


I wish you a bright future in front of the program ape, all the way to the north!