Common skills for JavaScript to improve performance summary of "classic" _javascript Skills

Source: Internet
Author: User
Tags access properties arithmetic bitwise

This article describes the common techniques for improving the performance of JavaScript. Share to everyone for your reference, specific as follows:

1. Attention Scope

as the number of scopes in the scope chain increases, the time to access variables outside the current scope is also increasing. Accessing global variables is always slower than accessing local variables because you want to traverse the scope chain .
1. It is always true to avoid global lookups where global objects are stored as local variables that will be used more than once in a function.

2. Avoiding The WITH statement with will create its own scope, thus increasing the length of the scope chain in which the code executes.

2. Choose the Right method

Part of the performance problem is related to the algorithm or method used to solve the problem.

1. Avoid unnecessary property lookup

In computer science, the complexity of the algorithm is represented by the O notation. The simplest and quickest algorithm is the constant value, that is, O (1). After that, the algorithm becomes more complex and takes longer to execute. Common JavaScript algorithm types are:

Constants: Regardless of the number of values, the execution time is constant. A general representation of a simple value and a value stored in a variable.

Logarithm: The total execution time is related to the number of values, but to complete the algorithm does not necessarily fetch each value. For example: two-point search

Linear: The total execution time and the number of values are directly related. For example: Iterate through all the elements in an array

Squared: The total execution time is related to the number of values, and each value must be fetched at least n times. For example: Insert sort

Cubic: The total execution time is related to the number of values, each value at least to get n squared

It is more efficient to use variables and arrays than to access properties on objects . Any property on an object takes longer to find than to access a variable or array, because you must search for a property that has that name in the prototype chain.

Generally speaking, as long as can reduce the complexity of the algorithm, it is necessary to minimize. Use local variables as much as possible to replace property lookups with value lookups. Further, if you can access a digitized array location, or you can use a named property, such as a NodeList object, use the array location.

2). Optimization cycle

A. Impairment iterations in many cases, the iterator, which begins at the maximum value, is more efficient than the constant decrement of the value in the loop.
B. Simplifying the termination condition because the termination condition is computed for each cycle, it must be guaranteed as fast as possible.
C. Simplifying the loop body is the most executed, so make sure it is optimized optimally. Make sure that there are no dense computations that can be easily removed from the loop.
D. The most common for and while loops used after the test cycle are the pre-test loops. And such as Do-while this post test loop, you can avoid the initial termination of the calculation of the condition, so faster.

3. Unwind loops When the number of loops is determined, eliminating loops and using multiple function calls is often quicker. such as the famous Duff device

4). Avoid double interpretation

When JavaScript code wants to parse JavaScript, there is a double explanatory penalty. The following example:

Eval ("alert (' Hello world! ')");
Some code evaluation

Correction:

Alert (' Hello world ');

var sayhi = new Function ("Alert (' Hello world! ')");   

Correction:

var sayhi = function () {
  alert (' Hellow world! ');


SetTimeout ("alert (' Hellow world! ')", 500);

Correction:

settimeout (function) ({
   alert (' Hellow world! ');
},500);

5). Other methods

native methods are faster--whenever possible, using native methods instead of using JavaScript to rewrite one . Native methods are written in a compiled language such as C + +, So it's a lot faster than JavaScript. The easiest thing to forget about JavaScript is the complex math that can be found in the Math object, which is much faster than any other method written in JavaScript, such as sine and cosine.

switch statements are faster--if you have a complex if-else statement, you can get faster code by converting to a single switch statement . You can also organize case statements in the most likely to most unlikely order, To further refine the switch statement.

bit operators are faster--when mathematical operations are performed, bitwise operations are faster than any Boolean operation or arithmetic. The selective operation of bitwise arithmetic can greatly improve the performance of complex computations. such as modulo, logic, and logic, or both, can be considered for substitution with bitwise operations.

3. Minimize the number of statements

1). Multiple variable declarations

Such as:

4 Statements---very wasteful
var count = 5;
var color = "Blue";
var values = [1,2,3];
var now = new Date ();

Optimization:

var count = 5,
color = "Blue", 
values = [1,2,3],
noiw = new Date ();

In most cases this optimization is very easy to do and is much faster than a single variable declaration.

2). Insert Iteration Value

Such as:

var name = Values[i];
i++;

Optimization:

var name = values[i++];

3). Using Arrays and object literals

Such as:

var values = new Array (); ---> var values = [];
var obj = new Object (); ---> var obj = {};

4. Optimizing DOM Interaction

1). Minimize field Updates

Once you need access to the DOM section that is already part of the displayed page, so you're doing a live update. The reason for the site update is to update the user's display immediately. Whether inserting a single character or removing an entire fragment has a performance penalty, Because the browser has to recalculate countless dimensions for updates.

Cases:

var list = document.getElementById ("MyList");
for (var i = 0;i < 10;i++) {
  var item = document.createelement ("li");
  List.appendchild (item);
  Item.appendchild (document.createTextNode ("Item" +i));
}

This adds 10 projects, with a total of 20 onsite updates to complete. The following methods are used to create document fragmentation:

var list = document.getElementById ("MyList");
var fragment = Document.createdocumentfragment ();
for (var i = 0; i < 10;i++) {
   fragment.appendchild (item);
   Item.appendchild (document.createTextNode ("Item" +i));
}
List.appendchlid (fragment);

In this example, there is only one field update, which occurs after all the items have been created. The document fragment is used as a temporary placeholder to place the newly created project. Then use AppendChild () to add all items to the list. Remember, when you pass in a document fragment to AppendChild (), Only the child nodes in the fragment are added to the target and the fragment itself is not added.

Once you need to update the DOM, consider using document fragmentation to build the DOM structure and then add it to an existing document.

2). Using innerHTML

There are two ways to create a DOM node on a page: Using a DOM method such as createelement (), AppendChild (), and using innerHTML for small dom changes, both methods are more efficient. For large DOM changes, Using innerHTML is much faster than creating the same DOM structure using a standard DOM method. Similarly, using innerHTML at one time is considerably faster than using innerHTML more than once.

3). Using Event proxies (Jane, abbreviated)

4). Note NodeList

minimizing the number of access nodelist can greatly improve the performance of your scripts.

The NodeList object is returned when the following conditions occur:

A. A call to getElementsByTagName ()
B. Gets the ChildNodes property of the element
C. Gets the attributes property of the element
D. Access to special collections such as document.forms, document.images, etc.

To understand that when using NodeList objects, reasonable use can greatly increase code execution speed.

The function throttling described earlier is also a very important aspect. This method is useful for multiple loops, especially when performance is very time-consuming.

PS: For JavaScript to compress, reducing the size of the code is also an effective way to improve JavaScript performance. Here we recommend 2 very useful compression tools:

JavaScript compression/formatting/encryption tool:
http://tools.jb51.net/code/jscompress

Jsmin Online JS compression tool:
Http://tools.jb51.net/code/jsmincompress

More readers interested in JavaScript-related content can view the site topics: "JavaScript switching effects and tips summary", "JavaScript Search Algorithm Skills Summary", "JavaScript animation effects and tips summary", " JavaScript error and debugging skills Summary, JavaScript data structure and algorithm skills summary, JavaScript traversal algorithm and skills summary and JavaScript mathematical calculation usage Summary

I hope this article will help you with JavaScript programming.

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.