High performance javascript -- programming practice

Keywords: Javascript IE

-setTimeout() and settimeInterval() pass functions instead of strings as arguments

Extension:
What's the difference between setInterval() and setInterval() using the setTimeout() method?

Accuracy problem?

Micro task and macro task problems?

Macro task: including overall code script, setTimeout, setInterval

Micro-task (micro task):Promise, process.nextTick, similar to the node.js version of "setTimeout", calls the callback callback function in the next cycle of the event loop.

Synchronous > asynchronous

Main task > micro task > macro task

console.log('script start');

setTimeout(function() {
  console.log('setTimeout');
}, 0);

Promise.resolve().then(function() {
  console.log('promise1');
}).then(function() {
  console.log('promise2');
});

console.log('script end');

Results: script start, script end, promise1, promise2, setTimeout

console.log('1');

setTimeout(function() {
    console.log('2');
    process.nextTick(function() {
        console.log('3');
    })
    new Promise(function(resolve) {
        console.log('4');
        resolve();
    }).then(function() {
        console.log('5')
    })
})
process.nextTick(function() {
    console.log('6');
})
new Promise(function(resolve) {
    console.log('7');
    resolve();
}).then(function() {
    console.log('8')
})

setTimeout(function() {
    console.log('9');
    process.nextTick(function() {
        console.log('10');
    })
    new Promise(function(resolve) {
        console.log('11');
        resolve();
    }).then(function() {
        console.log('12')
    })
})

Results: synchronization task 1, 7, subtask nextTick and promise.then()6,8, macro task setTimeout, as a new content 2, 4, 3, 5, 9, 11, 10, 12

-Try to create objects and arrays using direct quantities

// Use direct quantity
var obj = {
  name: 'zzz',
  age: 24,
};
var arr = ["nicholas", 50, true];

// Do not use direct quantity
var obj = new Object();
obj.name = 'zzz';
obj.age = 24;

var arr = new Array();
arr[0] = "nicholas";
arr[1] = 50;
arr[2] = true;

-Avoid repetitive work. When you need to detect the browser, you can use delayed loading or conditional preloading

The most common repetitive work is browser detection. Branch judgment based on browser functions results in a lot of code.

If a page calls addHandler function multiple times to add an event, the browser will make a judgment on which method to execute each time. In fact, the result of every judgment is the same. There are several ways to avoid it.

function addHandler(target, eventType, handler) { 
  if (target.addEventListener) {  // DOM2 Events
    target.addEventListener(eventType, handler, false);
  } else {  // IE
    target.attachEvent('on' + eventType, handler);
  }
}   

addHandler(document, 'click', function() {
  console.log('hello world');
});

Method 1: delay loading

Lazy loading, also known as lazy loading, lazy loading, etc. Delayed loading means that nothing is done until the information is used:

function addHandler(target, eventType, handler) { 
  if (target.addEventListener) {  // DOM2 Events
    addHandler = function(target, eventType, handler) {
      target.addEventListener(eventType, handler, false);
    };
  } else {  // IE
    addHandler = function(target, eventType, handler) {
      target.attachEvent('on' + eventType, handler);
    };
  }
  addHandler(target, eventType, handler);
}    

addHandler(document, 'click', function() {
  console.log('hello world');
});

addHandler(window, 'keydown', function() {
  console.log('key down');
});
//When the method is called for the first time, it will make a judgment to decide which method to use to bind the time handler, and then the original addHandler will be overwritten by the new addHandler function. In the last step, it will call the new function and pass in the original parameter. Each subsequent call to addHandler() does not detect again, because the detection code has been overridden by the new function.

//The first time will take a long time, because the task needs to be detected before calling to complete. It'll get faster later.

Method 2: conditional preloading

Conditional preloading is detected in advance during script loading without waiting for the function to be called:

var addHandler = document.addEventListener ? 
  function(target, eventType, handler) {
    target.addEventListener(eventType, handler, false);
  }:
  function(target, eventType, handler) {
    target.attachEvent('on' + eventType, handler);
  };    

addHandler(document, 'click', function() {
  console.log('hello world');
});
//This example is to check whether addEventListener() exists first, and then specify the function according to the result.

//Conditional preloading ensures that all function calls take the same amount of time, at the expense of being detected when the script is loaded. It is applicable to the scene where a function is about to be used and frequently appears in the whole page life cycle.

-When doing mathematical counting, consider using the binary form of bit operation that directly manipulates numbers

-js's original method is faster than any code you write. Try to use the original method.

In particular, mathematical operations. The method of the built-in Math object. dom operation, querySelector() and querySelectorAll()

The Math object is used to perform mathematical tasks.

Syntax for using the properties and methods of Math:

var pi_value=Math.PI;
var sqrt_value=Math.sqrt(15);

The Math object is not an object class like Date and String, so there is no constructor, Math(), and functions like Math.sin() are just functions, not methods of an object. Instead of creating it, you can call all its properties and methods by using math as an object.
https://www.w3school.com.cn/j...

Posted by Johntron on Thu, 21 Nov 2019 23:13:32 -0800