This is the fourth day of my participation in Gwen Challenge

As Web developers push JavaScript and browsers, there are some very specific patterns in JavaScript, both good and bad (in terms of JS performance). After all, JavaScript can be one of the most important components of the front-end.

These patterns come about because of the nature of JavaScript on the Web, where you have no choice on the front end and you can switch languages on the back end.



Avoid Double Evaluation

JavaScript, like many other languages, allows you to extract a string of code from a program and execute it dynamically

Four standard approaches to implementation:

  • The Function() constructor
  • eval()
  • setTimeout()
  • setInterval()

Example:

var num1 = 1,num2 = 6;
//eval() executes the code string
sum = eval("num1 + num2");
// The Function() constructor executes the code string
sum = new Function("num1"."num2"."return num1 +num2");
//setTimeout() executes the code string
setTimeout("sum = num1 +num2".100);
//setInterval() executes the code string
setInterval("sum = num1 +num2".100)
Copy the code

When executing another piece of JavaScript code within JavaScript code, there is a performance cost of double evaluation

The above code first evaluates in the normal way and then initiates another evaluation on the code contained in the string during execution

Double evaluation and direct evaluation performance comparison: (if you feel that the test code is wrong, you can tell me in the comment section, constantly correct)

var num1 = 1,num2 = 6;
console.time('Double evaluation')
for (var i = 0; i < 10000; i++) {
   //eval() executes the code string
    sum = eval("num1 + num2");
}
console.log(sum)
console.timeEnd('Double evaluation')
console.time('Directly evaluate')
for (var i = 0; i < 10000; i++) {
   sum = num1 + num2;
}
console.log(sum)
console.timeEnd('Directly evaluate')
Copy the code

Chrome:

Internet Explorer:

Firefox:

As you can see from the above tests, double evaluation is not nearly as fast as direct evaluation.

Reason: Each call to Eval () creates a new interpreter/compiler instance, as do the other three, so this inevitably leads to slower code execution

Like setTimeout and setInterval, it is best to pass the first argument to a function rather than a string. Of course, who does not write function on the delay function to write string code ah! Dog. JPG

Avoiding double evaluation can greatly improve the performance efficiency of JavaScript runtime

Use Object/Array direct quantities

There are many ways to create objects and arrays in JavaScript, but using objects and arrays directly is the fastest way


New Object assignment vs. Direct Object assignment:

console.time('Object direct quantity')
for (var i = 0; i < 10000; i++) {
    var obj = {
        name:'City plane'.age: 25.sex: 'male'}}console.timeEnd('Object direct quantity')

console.time('New Object mode')
for (var i = 0; i < 10000; i++) {
   var obj = new Object(a); obj.name ='City plane';
   obj.age = 25;
   obj.sex = 'male';
}
console.timeEnd('New Object mode')
Copy the code

Chrome:

Firefox:

Because Internet Explorer is going to retire in 2010, some Microsoft systems will not support Internet Explorer 11, so the test results of Internet Explorer are not provided here, although it is the same, you can try it yourself



Array directly compared to the new Array (if you feel that the test code is not correct, please let me know in the comments section, and keep correcting)

<script>
    console.time('Array direct quantity')
    for (var i = 0; i < 10000; i++) {
        var arr = [30.'1'.null]}console.timeEnd('Array direct quantity')
    console.time('New Array mode')
    for (var i = 0; i < 10000; i++) {
       var arr = new Array(a); arr[0] = 30,
       arr[1] = '1',
       arr[2] = null
    }
    console.timeEnd('New Array mode')
 </script>
Copy the code

Chrome:

Here’s the highlight, and I was surprised by the results in Firefox:

Firefox:

Firefox took longer to test the array directly.

And I quickly tested itIE browser

IE is also consistent with the previous results, so what causes firefox to behave differently?

I typed the code directly into the Firefox control bar and found it correct

So I have two guesses: 1. Not enough data to test and 2. Firefox engine tweaks

I then adjusted the number of loops, but the Firefox browser console found little difference in performance, with multiple tests and arrays being slower

I then switched the position of the test method and had the new Array execute the new test code on top first:

<script>
    console.time('New Array mode')
    for (var i = 0; i < 10000; i++) {
       var arr = new Array(a); arr[0] = 30,
       arr[1] = '1',
       arr[2] = null
    }
    console.timeEnd('New Array mode')
    console.time('Array direct quantity')
    for (var i = 0; i < 10000; i++) {
        var arr = [30.'1'.null]}console.timeEnd('Array direct quantity')
</script>
Copy the code

Firefox:

The result is obvious: array direct performance is faster

Boy, am I straight? The horn came out

This is the Firefox engine running JS “small egg”, the Internet looked for along while the data did not find, may be the engine loaded when the difference

The test then enters the test directly on the console



Avoid reinventing the wheel

Performance optimization is all about avoiding duplication of effort

Method:

  • Lazy loading

    • When the method is first called, the check determines which method to use to bind the event handler, and then the original function is overwritten by the new function
    • The first invocation of a delayed function takes a long time
    • When a function is not called immediately in a page, lazy loading can be used to optimize performance
  • Conditional preloading

    • Checking before the script loads is useful when a function is about to be used and occurs frequently throughout the life of the page
  • Bit operation

    • There are also and or operations in JavaScript, which can speed up the performance of JS
  • A native method

    • No matter how optimized your JavaScript code is, it can’t be faster than the native methods provided by JavaScript engines
    • JavaScript native methods are still extracted in the browser and compiled into machine code
    • Math methods, for example, can be used to perform complex Math operations using methods in the built-in Math object
    • Beginner tutorial: JavaScript Math object







section

Avoid double-evaluation methods, such as eval and Function constructors, if you must. The delay function remembers to write the method instead of the code string as its first argument.

Object and Array arrays perform better than new objects and arrays (although Array arrays are a bit strange in Firefox).

What can be optimized when writing code