JS Performance Optimization — JS code optimization

Time:2021-10-18

catalogue

  • Introduction to performance testing tools

    • Use process
  • JS code optimization

    • Use global variables with caution
    • Cache global variables
    • Adding methods through prototypes
    • Avoiding closure traps
    • Avoid using property access methods
    • For loop optimization
    • Select the optimal cycle method
    • Node addition optimization
    • Clone optimization node operation
    • Replace new object directly

Introduction to performance testing tools

Performance tools can help us know how to write code is more efficient. Its essence is to collect a large number of execution samples for mathematical statistics and analysis.

  • Use basedBenchmark.jsofjsperf.comCompleted, this website has been502, you can deploy locally if you are interestednpm i benchmark --save-devTake a look
  • Alternative websites can be usedjsbench.me

Use process (because it has been 502 not used at present)

  • Sign in
  • Fill in detailed test case information(title/ slugIt is a short name, which will generate a web address, so it can’t be repeated with others.)
  • Fill in preparation code(DOM(often used during operation)
  • Fill in necessarysetup(start operation) andteardown(destroy after execution) code

JS code optimization

There are many kinds of code optimization. Let’s briefly introduce a few first, which is also an accumulation process. What we encounter in the future will be added here

Use global variables with caution

Why use it with caution?

  • Global variables are defined in the global execution context and are the top of all scope chains. Every time we look, we find the top from the part,Time will be consumed
  • The global execution context exists in the context execution stack until the program exits,Waste of memory space
  • If a variable with the same name appears in a local scope, theMask or pollute the whole situation

The following figure does not look at the function, but just wants to explain the difference between using global variables and not using global variables:

JS Performance Optimization -- JS code optimization

Cache global variables

Cache global variables that cannot be avoided in use locally. As shown below, the performance of cached variables is better than that of non cached variables.

JS Performance Optimization -- JS code optimization

Adding methods through prototypes

Try to add the methods required by the instance object on the prototype object, rather than adding methods inside the constructor.

JS Performance Optimization -- JS code optimization

Avoiding closure traps

Closures can access data in the internal scope of a function in an external scope.

  • Closures are a powerful syntax
  • Improper use of closures is prone to memory leaks
  • Don’t close for closure

Case analysis

The following code forms a closure,elexistencefooWithin the scope of the function, andonclickThe anonymous function pointed to is a new scope, which referencesfooIn scopeid, can cause memory leaks.

function foo() {
    var el = document.getElementById('btn')
    el.onclick = function() {
        console.log(el.id)
    }
}

foo()

If you want the memory not to leak, you can use it after useelSet asnull

function foo() {
    //The code to the right of the equal sign already exists in the 'DOM' tree, and 'El' is a new reference.
    //This element has been referenced by us twice. Even if the 'DOM' is' removed ', it will also be referenced in the code' El '. You can only manually clear the code below.
    var el = document.getElementById('btn')
    el.onclick = function() {
        console.log(el.id)
    }
    
    //If you want to avoid disclosure, add the following
    el = null
}

foo()

Avoid using property access methods

JavaScripObject oriented in t

  • JSNo property access method is required, and all properties are externally visible
  • Attribute access methods only add a layer of redefinition, and have no access control

JS Performance Optimization -- JS code optimization

For loop optimization

Put the arraylengthAlso stored in a variable.

JS Performance Optimization -- JS code optimization

Select the optimal cycle method

forEachforfor-inComparison of

JS Performance Optimization -- JS code optimization

Node addition optimization

The addition of nodes must have reflow and redraw

document.createdocumentfragment()Method creates a virtual node object, a new document fragment, which contains all properties and methods.
In this way, the addition of nodes can be merged and the number of nodes can be reducedDOMRedrawn.

JS Performance Optimization -- JS code optimization

Clone optimization node operation

Existing properties and contents do not need to be added again

JS Performance Optimization -- JS code optimization

Replace new object directly

When we define objects and arrays, we can usenewLiteral values can also be used.

JS Performance Optimization -- JS code optimization