JS Performance optimization

Source: Internet
Author: User

This paper mainly introduces JS performance optimization related knowledge.

Scope-Related:

1. Avoid global lookups

We know that the scope chain is local in front, global in the back, then the access to global variables need to traverse the scope chain, its cost is naturally greater than the local.

  

2. Avoid with statements

With creates its own scope, which means that it increases the length of the scope chain in which the code executes, causing additional scope chain lookups.

Choose the correct method:

1. Avoid unnecessary property lookups

In computer science, the complexity of the algorithm is represented by an O symbol. Here I simply describe it in words.

The simplest algorithm is a constant value, that is, O (1), regardless of the number of values, the time of execution is consistent, generally used to represent simple values and values stored in the variable.

O (log n) the total execution time and value of the proficiency correlation, but to complete the algorithm is not necessarily to obtain each value. Example: Two-point lookup

O (n) The total execution time and the number of values are directly related. For example, iterate through all the elements in an array.

O (square of N) The total execution time is related to the number of values, and each value is just to get n times. For example: Insert sort.

Light said I believe most of them are a face, the following with some JS code to understand intuitively:

  

Let value = 5let num = ten + valueconsole.log (num)

This code is 4 times the constant value of the lookup, 5, 10, Vallue, NUM, the overall complexity of this code is considered O (1), access to the array element is also considered O (1)

  

Let values = {One:1,two:2}let num = values.one + values.twoconsole.log (sum)

Accessing a property on an object is considered an O (n) operation, because a property with that name must be searched in the prototype chain, which uses two property lookups to calculate the value of num, and if only one or two times does not cause significant performance problems, it will be obvious once more.

We want to pay attention to the multiple attribute lookups for a single value. Like what:

  

Let query = window.loaction.href.substring (window.loaction.href.indexOf ('? '))

Here we repeat the Window.loaction.href this property to find, the statement's property lookup total of 6 times (can see a few.), repeated once, resulting in a lack of performance, the correct way is to window.loaction.href this attribute value is first stored with a constant, so that the Operation is O (1) operation.

2. Optimized circulation

A, decrement iteration, in many cases, the iterator that continuously values the value in the loop is more efficient starting from the maximum value.

b, simplify the termination conditions, each cycle process will be calculated, so as far as possible to simplify the termination conditions, that is, preferably O (1) operation

C, simplify the circulation body, the loop body execution is the most, so also want to simplify as far as possible, ibid.

D, after the use of the test cycle, the most common is for and while loop, these 2 are the front test loop. The post-test cycle, such as do-while, avoids the calculation of the initial termination condition and therefore runs faster.

3. Expand Cycle

When the number of loops is determined, eliminating loops and using multiple function calls tends to be faster, eliminating the extra overhead of establishing loops and processing termination conditions. If the number of iterations cannot be determined beforehand, you can take a look at a technique called the Duff device, which is not elaborated in detail here.

4. Avoid double interpretation

This avoids the need to install a JavaScript-interpreted string.

5. Other matters needing attention

The native method is faster, the switch statement is faster than a series of if-else, and the bitwise operator is faster.

Minimum number of statements

1. Variable declaration

  

var a;var b;var C,    D;

The former is 2 statements, and the latter is a statement.

2. Insert Iteration Value

  

var name = Value[i]    i++var name = value[i++]

The former and the latter do things the same, + + is the suffix operator.

3. Using Arrays and object literals

  

var arr = new Array () arr[0] = 1arr[1] = 2var arr = [1, 2]

The former 3 statements, the latter only 1.

  

Dom Interaction Optimization

In all aspects of JS, Dom is the slowest part! Dom operations and interactions consume a lot of real-world information, and it is particularly important to understand how to optimize interaction with the DOM.

1. Minimize on-site updates

The site update means that the DOM part that you access is part of the page that has been displayed.

For example, when you iterate over a DOM node, you can use the document fragment to construct the DOM deconstruction, and then Dom render. Here's the code:

var list = document.getElementById (' myList '),    fragment = Documemnt.createdocumentfragment (),    item,i;for (i= 10; i>=0; i++) {    item = document.createelement (' li ');    Fragment.appendchild (item)    Item.appendchild (document.createTextNode (' item ' + i));    } List.appendchild (fragment);

In this example, there is only one live update.

2. Using innerHTML

innerHTML is also a method of creating DOM nodes, compared to createelement, which has the advantage that large DOM changes are more efficient than standard DOM methods. Because it is not a DOM call based on JS, it is created by the DOM inside the HTML parser created in the background.

While using innerHTML, we should also pay attention to minimizing the number of times it is called.

3. Using Event proxies

A page is a negative correlation between the number of event handlers and the speed at which the page responds to user interaction, so we'd better use the event proxy for user interaction.

Any event that can be bubbled can be handled not only on the event target, but also on any ancestor node of the target. If possible, attach event handlers at the document level, which can handle the entire page of events.

4, pay attention to Htmlcollection

The cost of querying htmlcollection is expensive, and minimizing the number of accesses to htmlcollection can greatly improve the performance of the script.

JS Performance optimization

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.