This is the 8th day of my participation in the More text Challenge. For details, see more text Challenge

This article mainly introduces some performance optimization recommendations, including coding, animation performance, page launch performance optimizationCopy the code

coding

Avoid global lookup

Using global variables and functions is more expensive than local ones. You can store global variables in local variables and call them later. It is always good to save global objects that are called multiple times within a function as local variables [1]

    // Look globally for document
    function updateElement() {
        var p = document.getElementsByTagName('p');
        var title = document.getElementById('title');
        
        p.forEach(val= > {
            val.innerHTML = document.title;
        })
        title.innerHTML = 'world';
    }
    
    // Local lookup
    function updateElement() {
        var doc = document;
        var p = doc.getElementsByTagName('p');
        var title = doc.getElementById('title');
        p.forEach(val= > {
            val.innerHTML = doc.title;
        })
        title.innerHTML = 'world';
    } 
Copy the code

Avoid with statements

I’m sure you’ve heard of the with statement. It creates its own scope, thus increasing the length of the scope chain of code executing within it, so that code executing inside the with statement is slower than code executing outside.

Avoid unnecessary attribute lookups

To reduce the complexity of the algorithm, replace attribute lookups with value lookups by using local variables as much as possible.

    / / code 1
    var a = 1;
    var b = 100 + a;
    console.log(b);
    
    / / code 2
    var arr = [1.100];
    var b = arr[0] + arr[1];
    console.log(c);
Copy the code

So the efficiency of the above code is the same as that of code 1 which performs four constant lookups: a, number 1, number 100, and number b with time of O(1) and code 2 with time of O(1)

If the variable lookup is declared in an object, it will take longer than if the variable is accessed in an array, for example

    var obj = { a: 1.b: 100 };
    var result = obj.b - obj.a;
    console.log(result);
Copy the code

The time complexity of the above code to access the variable is O(n), and the object must search for the attribute in the prototype chain when searching, so the more object properties, the longer the search time.

Simplify loop termination conditions

Place the value of the condition that terminates the loop in the declaration variable, avoiding attribute lookups or other O(n) operations

    // before
    const arr = [1.2.3.4.5.6.7.8.9.0];
    for (let i = 0; i < arr.length; i ++) {
        ...
    }

    // after
    const arr = [1.2.3.4.5.6.7.8.9.0];
    for (let i = 0, len = arr.length; i < len; i ++) {
        ...
    }
Copy the code

Avoid double interpretation

    / / avoid!!!!!!
    const code = `var a = 0; console.log(a)`;
    eval(code);
    var test = new Function(code);
    setTimeout(code, 1000);
Copy the code

Multiple variable declarations

The number of code statements also affects the speed of the actions being performed. A single statement that completes multiple operations is faster than multiple statements that complete a single operation

    // before
    var a = 1;
    var b = 'a';
    var c = {};
    var d = [];
    
    // after
    var a = 1,
        b = 'a',
        c = {},
        d = [];
Copy the code

Use arrays and object literals

As you can see from the above, multiple statements for a single operation are relatively fast, so you can do the same when initializing an object or array

  // before
  var arr = [];
  arr[0] = 'aaa';
  arr[1] = 'bbb';
  arr[2] = 'ccc';
  
  var obj = {};
  obj.a = 'aaa';
  obj.b = 111;
  obj.c = () = > {};
  
  // after
  var arr = ['aaa'.'bbb'.'ccc'];
  var obj = {
      a: 'aaa'.b: 111.c: () = >{},}Copy the code

Optimizing DOM interaction

Minimize field updates

Rendering the interface in the browser is a very performance consuming business, so it is important to reduce the frequency of inserting DOM nodes. Such as:

    var list = document.getElementById('list');
    
    for (let x = 0, max = 10, x < max; x++) {
        var li = document.createElement('li');
        li.innerHTML = x;
        list.appendChild(li);
    }
Copy the code

The above code repeats 10 nodes into the list, and each time the node is inserted, the browser recalculates the location of the page. It’s very performance intensive. The solution is to use createDocumentFragment

    var list = document.getElementById('list');
    var fragment = document.createDocumentFragment();
    
    for (let x = 0, max = 10, x < max; x++) {
        var li = document.createElement('li');
        li.innerHTML = x;
        fragment.appendChild(li);
    }
    list.appendChild(fragment);
Copy the code

With the improvement of document fragment, there is only one node insertion operation, effectively reducing the performance cost caused by node update. In addition, using innerHTML can produce a similar effect, but string concatenation comes with a performance penalty.

    var list = document.getElementById('list');
    var html = ' ';
    for (let x = 0, max = 10, x < max; x++) {
        html += `<li>${ x }</li>`;
    }
    list.innerHTML = html;
Copy the code

Using an event broker

As you can see from the publish-subscribe pattern, as the number of listeners increases, so does the memory, making the page performance worse. When you click on a list event, you can use the event broker to reduce the listener declaration.

    /** * 
      
    *
  • * ... *
  • *
*/
// before var list = document.getElementsByTagName('li'); for(let x = 0, len = list.length; x < len; x++) { list[x].onclick = () = >{... }}// after var ul = document.getElementById('#ul'); ul.addEventListener('click'.(e) = > { let target = e.target; switch(target.id) { case "li_1":...case "li_2":... }});Copy the code

Optimize startup performance

  • Use DNS to preobtain files
  • Used in scripts that require asynchronous executiondeferasyncProperty loading. This allows the HTML parser to process the document more efficiently.
  • Use Web Workers to run long duration JavaScript code logic
  • All data processing that can be parallel should be parallel. Don’t crunch data clumps on top of each other; if possible, crunch them all at once
  • In the HTML file you launch, don’t include scripts or stylesheets that don’t appear in the critical path. Load them only as needed [2]

summary

If you found the article helpful, you can encourage the author with a like. If you want to learn more about JavaScript or Node, you can click here.

If there are any inaccuracies or errors in this article, please note them in the comments section.

reference

  1. JavaScript advanced programming
  2. Web performance