Js Code Optimization for front-end performance

Source: Internet
Author: User

Js Code Optimization for front-end performance
Scope

During JavaScript Execution, a scope chain is built for variable parsing. The Global execution context has only one object variable and defines all the variables and functions in js. When a function is created, a new local scope is generated, and the parameters named this, arguments, and other local variables and functions are initialized. At the top of the entire scope chain is the scope of the activity. The variable parsing sequence is to first look up from the current scope. When the result is found, the query is terminated. Otherwise, the query continues to go up to the scope level, until the global scope. Therefore, if a large variable spans multiple levels of scope during parsing, the performance will be affected. The performance improvement of the scope is to reduce the cross-level.

Use local variables

The speed of reading and writing local variables is the fastest. They exist in the current active scope. However, this feature is not obvious in Google chrome and Safari4 + browsers, because the v8 and Nitro engines they use are very fast in variable parsing, the number of layers of variable Parsing is reduced to a little higher in speed. But other browsers are very
Obviously, especially in IE8 and FireFox browsers.
A good principle is to store any variables that are not in the current scope and must be used twice or more times with local variables.

Change Scope

The with statement switches the scope of the current execution in JavaScript, and the corresponding object attributes can be accessed in this statement block. But in fact, this method inserts a new scope before the scope chain of the execution context. Therefore, when you start to enter the with statement, parsing local variables in the current execution context will span Multiple scopes, resulting in performance loss. Therefore, avoid using the with statement.

Data Access

There are four ways to read and write data:
-Literal
-Variable
-Array
-Object Attributes
The literal and local variables can basically be ignored. Access to these data can basically increase the proportion of performance. The real difference is that data is read and written from the attributes of arrays and objects. To obtain data from these two methods, you need to search for the location, including using index subscript and attribute name. When searching, the most time-consuming is the object attributes, especially the time-consuming search for multi-level attributes.
To solve this problem, the best way is to use local variables to store any object attributes or array elements that are used once or more.

// Function procee (data) {if (data. count> 0) for (var I = 0; I <data. count; I ++) processData (data. item [I]);} // optimized version function () {var cnt = data. count; if (cnt> 0) for (var I = 0; I <cnt; I ++) processData (data. item [I]);}

In addition, it is particularly important to store local variables when processing DOM-related objects, because attribute access to each DOM-related object is actually a DOM query, you need to minimize attribute access to such large objects and use local variables for temporary storage.

Process Control Condition Statement

When multiple discrete values are used for comparison, using the if statement may result in a large number of comparisons, so it is better to use the switch statement. It is also a reinforcement method for if statements to split by using the binary method. At the same time, you can calculate the frequency of each comparison value and place the value of a large frequency in the front.
For the above changes, you can use the index under the array for quick selection, instead of one by one comparison. However, this must ensure that the number of discrete values cannot be too large and can be replaced by index values.

Loop

In JavaScript, for, while, and do-while loops are stored using local variables if the conditions in these loops contain the attributes of objects. Otherwise, as the number of loops increases, it takes a lot of time to access object attributes each time.
Another way to speed up the loop is to sort the traversal order of the loop in reverse order, which will save about 50% of the time (depending on the complexity of processing in the loop) than the sequential traversal ).
In JavaScript, there is also a for-in loop used separately to traverse each attribute of an object. This is a very effective method when traversing an object with a location attribute, however, this method is much slower than a normal loop because it traverses the object prototype and all attributes of the entire prototype chain, which is very time-consuming. For known objects, it is a good choice to replace for-in with three common loop statements.
Scatter loop:
For Loop statements with a small number of cycles, you can directly repeatedly call loop statements to eliminate loop statements. However, for loops with a large number of times, Tom Duff first proposed the method of cracking the loop in C language, known as Duff's Device. Jeff Greenberg, the first publisher of The JavaScript language, rewritten the Duff's Device of the JavaScript version:

var iter = Math.ceil(values.length / 8);var left = values.length % 8;var i = 0;if (left > 0){    do{        process(values[i++]);    }while(--left > 0);}do{    process(values[i++]);    process(values[i++]);    process(values[i++]);    process(values[i++]);    process(values[i++]);    process(values[i++]);    process(values[i++]);    process(values[i++]);}while(--iter > 0);

In the preceding method, the number of cycles is reduced to the value of 8, which is the optimal value obtained from multiple experiments. When the number of objects to be traversed is very large, the optimization using the above method will be much faster than the normal loop.

String-optimized string connection

When all browsers process less than 20 characters and less than 1000 connection operations, they are very fast. In this case, you do not need to consider it.
When the string is too long or there are too many connection operations, you need to consider performance issues. For ie browsers, the string-connected operator "+" is relatively performance-consuming. Therefore, the following methods are generally used for optimization:

var buf = [], i = 0;buf[i++] = Hello;buf[i++] =  ;buf[i++] = world;var text = buf.join();

However, after FireFox introduces the browser to optimize string operations, Chrome, Opera, Safari, and IE 8 + have all optimized string operations. Therefore, you do not need to consider the preceding method. In particular, the "+" operator After Chrome and Opera optimization is very fast.

Trim operations on strings

Because JavaScript does not have a native trim function, the above operations are generally performed using regular expressions:

function trim (s){    return s.replace(/^s+|s+$/g, );}

Here, the regular expression uses or. In fact, there are two modes, and a g modifier, indicating global search. To speed up, Steven Levithan provides the optimized trim function:

function trim(s){    s = s.replace(/^s+/, );    for(var i = s.length - 1; i >= 0; i--){        if (/S/.test(s.charAt(i))){            s = s.substring(0, i+1);            break;        }    }    return s;}

Here, the regular expression is simplified, and empty characters at the end are checked one by one.
The premise of the above optimization is that they use a very large frequency, the performance improvement is relatively large. In addition, the new ECMAScript 3.1 defines the built-in trim function, which is very fast.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.