How to improve the performance _javascript skills of JavaScript code

Source: Internet
Author: User

I was going to summarize this code performance article after I wrote the maintainability code article, delayed a few days, was also decided to update an article every day, because the previous owed too many things did not summarize, learned things did not go to sum up really quickly forget, record in your brain left a deeper impression, In particular, these maintainability codes, performance, and so on, when a habit is formed in your mind, you are a cow! Here also want to give beginners a suggestion: More summed up what you have learned, because this is actually learning new knowledge! OK, enter our topic: How to improve the performance of the JS code.

1. Optimizing Dom Interaction

DOM is closely related to our pages, and the browser renders the page, which is the rendering of parsed DOM elements, and DOM operations and interactions consume a lot of time because they often need to render the entire page or part of it. Further, seemingly subtle operations may take a lot of time to execute, because DOM has so much information to handle, so we should optimize DOM-related operations as much as possible and speed up the rendering of the page by browsers! Why do some DOM operations affect page performance, and you can view some of the articles I wrote about the principles of the browser:

OK, to optimize DOM operations, we have several main ways:

1.1 Minimize field Updates

What is a live update of the DOM: it needs to be updated immediately for the display of part of the page that is already displayed in the DOM section. However, each change, whether it is inserting a single character or an entire fragment, has a certain performance penalty because the browser needs to recalculate countless dimensions to update it (read the relevant knowledge:). As a result, the more field updates take place, the longer the code executes, and the faster the code executes, as follows:

var list = document.getElementById (' mylist '),
      item,
      i;
for (i = 0; i < i++) {
  item = document.createlement (' li ');
  List.appendchild (item);
  Item.appendchild (Document.creattextnode (' item ' + i));
}

This code adds 10 items to the list mylist, and does not add a single item to be updated 2 times: Add elements and add text nodes, so this operation one needs to complete 20 field update, each update will lose performance, visible such code is relatively slow to run.

The workaround is to use document fragmentation to indirectly change the DOM element:

var list = document.getElementById (' mylist '),
      fragment = Document.creatdocumentfragment (),
      item,
      i;
for (i = 0; i < i++) {
  item = document.createlement (' li ');
  Fragment. appendchild (item);
  Item.appendchild (Document.creattextnode (' item ' + i));
}
List.appendchild (fragment);

Code like this just needs a live update. Remember that when the document fragment is passed to AppendChild (), only the child nodes in the document fragment are added to the target element and the fragment itself is not added.

Now, you should understand that you use the loop directly to modify the DOM node to check how sorry the browser is, ' (∩_∩).

1.2 Using InnerHTML

In addition to the createlement () and appendchild ()-combined methods used in the above code to create DOM elements, there are also created by assigning values to innerHTML. For small DOM changes, the two methods are actually more efficient, but for a large number of DOM node changes, the latter is much faster than the former! Why pinch?

Because when we assign a value to innerHTML, the background creates an HTML parser, and then uses the internal DOM call to create the DOM structure, not JavaScript based DOM calls, so the execution code is much faster because the internal method is compiled rather than interpreted to execute.

Rewrite the above example with innerHTML:

  var list = document.getElementById (' mylist '),
       html = ',//declaring an empty string
        i;
  for (i = 0; i < i++) {
    html = ' <li>item ' + i + ' </li> ';
  }
  list.innerhtml = html; Here remember innerHTML HTML four letters to capitalize!

This approach also has only one site update, and performance is better than the previous one! Although there is a loss of performance on the link to the string.

1.3 Using event agent/event delegates

Event handlers provide interactivity for Web applications, so many developers will indiscriminately add a large number of handlers to the page, with the problem that the number of event handlers on a page is directly related to the overall performance of the page. Why pinch?

First, the event handler corresponds to at least one function, each function in JS is an object, will occupy memory, the more objects in memory, the worse performance.

Second, we have to specify all the event handlers in advance, which leads to an increase in DOM access, delays the interaction-ready time of the entire page, and makes the page respond to user actions relatively slow.

So reducing the event handler can also make our page more New! Use the event delegate potential.

The principle of an event delegate is actually event bubbling, which allows you to manage all events for a type of operation by specifying only one event handler. For example, the Click event is bubbling to the document level, which means that we do not have to add events for each element, simply add an event handler to the higher level of the element, and then use the properties or methods of the event object to determine the currently clicked element and respond accordingly. I'm not going to start talking about it, beginners can check event bubbling knowledge by themselves.

2. Scope is important

Speaking of scopes, it's easy to think of scope chains (scope chain), we know that to search for a variable, where the execution environment is going to search for this variable along this scope, there are many variables on the scope chain, then we have to traverse, the traversal takes time, and the more you go up and look up the more time you need. , if we can reduce this time, our code execution efficiency can not improve it?

So smart, OK, I'll see how to reduce this time:

2.1 Avoid Global Lookup

This is a key to performance optimization, said above, the more the more search time, that is, to find global variables and functions more than the local! Look at the code:

function UpdateUI () {
  var IMGs = document.getelementbytagname (' img ');
  for (var i = 0, LNG = imgs.length;i < Lng;i + +) {
    Imgss[i].title = document.title + ' image ' + i;
  }
  var msg = Docuement.getelementbyid (' msg ');
  msg.innerhtml = ' update complete ';
}

This code is very normal Ah! That's what I used to do. But we are careful to see that this code has three references to the global variable document, if we have a lot of pictures on our pages, the document in the for loop will be executed hundreds of times, and every time you need to look in the scope chain, where are you going, I haven't ... Stop!.

We can save a reference to the document by creating a local variable in the function so that we do not have to go to the global variable to find any references to the document anywhere in the function. This improves the performance of the code, looking at the code:

function UpdateUI () {
  var doc = document;//save document in local variable doc
  var IMGs = doc.getelementbytagname (' img '); C12/>for (var i = 0, LNG = imgs.length;i < Lng;i + +) {
    Imgss[i].title = doc.title + ' image ' + i;
  }
  var msg = Doc.getelementbyid (' msg ');
  msg.innerhtml = ' update complete ';
}

So, in our development, if we use a global variable in a function, we save it in a local variable!

2.2 Avoid using the WITH statement

Using the WITH statement to extend the scope, look for variables the same time, we generally do not use, so do not expand. The workaround is to save the global variable in a local variable, just like the example above!

3. Optimization cycle

Cycle in the programming is commonplace, in JS can also be seen everywhere, cycle experience repeatedly execute the same piece of code, the execution time has been cumulative, so can be optimized for the loop body code can also greatly reduce the execution time! How to optimize? Four different ways.

3.1 Value-reduction iterations

This is generally the case when we write iterators (cyclic conditions) (var i = 0;i < 10;i + +), starting at 0 and adding to a specific value. In many cases, however, it is more efficient to use a decrement iterator in a loop. I tested the next, if the loop body is not complicated, the two are similar!

Value-Added iterations-Low efficiency for
(var i = 0;i < items.length;i++) {
  dosomething (items[i)); 
}
Reduced-value iterations--High efficiency for
(var i = items.length-1;i >= 0;i--) {
  dosomething (items[i]); 
}

3.2 Simplifying termination conditions

Because each loop computes the termination condition, it must be guaranteed to execute as much as possible. This is primarily to avoid finding other DOM elements and their properties.

 Look at the termination condition, each loop needs to query items and their length properties for
(var i = 0;i < items.length;i++) {
  dosomething (items[i]); 
}

Save the Items.length value in the local variable LNG. For
(var i = 0,lng = Items.length;i < lng;i++) {
  dosomething (items[i]); 

3.3 Simplified Circulation body

Reason and above, so avoid a lot of intensive operation in the circulation body.

This is actually with the above: 1.1 Minimize field updates. Is the same as the optimization method. can go back and see.

4. Basic algorithm optimization

In computers, the complexity of the algorithm is expressed in O. The following are some of the common types of algorithms in javascript:

O (1): constant, regardless of the number of values, the execution time is constant, such as simple values and values stored in the variable.
O (log n): logarithm, total execution time and quantity, but not necessarily getting every value, such as: Binary lookup
O (n): Linear, total execution time and quantity directly related, such as: traversal
O (n*n): squared, total execution time and quantity related, each value gets at least n times, such as: Insert sort
OK, with the knowledge above, we can do some algorithmic optimizations on JavaScript. Look at the code:

var value = 5;
var sum = value + ten;
alert (sum);

This code has 4 times constant value lookup: Number 5, variable value, Number 10, variable sum, the algorithm complexity of this code is O (1). Another example:

var value = [10,5];
var sum = value[0] + value[1];
alert (sum);

Accessing an array element in JavaScript is also an O (1) operation, as is the case with simple variable lookup efficiency. Look again:

var value = {One:10,two:10};
var sum = value.one + value.two;
alert (sum);

The expression is that accessing properties on an object is less efficient than accessing arrays and variables. Because this is an O (n) operation. You need to find this attribute in the object's prototype chain, which takes more time.

Well, after this is not a feeling of light ah. In fact, we talked about to the common use of the global properties in a local variable is based on this principle, access to the global property is an O (n) operation, while the access variable is an O (1) operation, loudly tell me, excavator which home strong Ah!

5. Minimize the number of statements

Earlier optimizations are almost all about streamlining optimization statements, and yes, I think the quality and quantity of code is the criterion of performance. Some of the code-quality-related optimizations are discussed here, which is about optimizing the number of code.

5.1 Thin Variable Declaration

Use 5 statements to declare 5 variables
var count = 5;
var color = ' Red ';
var values = [1,2,3];
var now = new Date ();

With 1 statements declaring 5 variables, note that each variable is separated by a comma with
var count = 5,
  color = ' red ',
  values = [1,2,3], now
  = new Date ();

5.2 Using arrays and object literals

Creating two objects----bad way
//one four statements
var values = new Array ();
Values[0] = 123;
VALUES[1] = 456;
VALUES[2] = 789;
Two four statement
var person = new Object ();
Person.name = ' Jozo ';
Person.age =;
Person.sayname = function () {
  alert (this.name);
};
Create two objects----recommended
//one 1 statements
var values = [123,456,789]
//two 1 statement
var person = {
  name: ' Jozo ' ,
  age:21,
  sayname:function () {
  alert (this.name);
};

6. Other

Write tired, if there is not the correct place please correct me oh, there are some other optimization, the next article to continue!

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.