Web Performance Tuning series 10 tips for improving JavaScript performance _javascript tips

Source: Internet
Author: User
Tags define local

Nicholas Zakas is a JS master, Yahoo! The front page of the main process. He is the author of High-performance Javascript, a book that is worth reading by every programmer.

When it comes to JS performance, Zakas is almost what you're looking for, and in June 2010 he published a speech called "Speed up Your Javascript" in Google Tech talk.

But Javascript performance optimization is by no means a written technique, Nicholas's technical evolution lists 10 suggestions to help you write efficient JS code.

1. Define Local variables

When a variable is referenced, JavaScript looks for the variable in different members of the scope chain. A scope chain is a collection of currently active variables that contain at least two parts in a variety of mainstream browsers: a set of local variables and a collection of global variables.

Simply put, if the JavaScript engine searches in the scope chain more depth, then the operation will consume more time. The engine first looks for local variables from this, then function arguments, locally defined variables, and finally traverses all global variables.

Because local variables are at the start of this chain, it is always better to find local variables than to find global variables. So when you want to use a global variable more than once, you should define it as a local variable, like this:

var blah = document.getElementById (' MyID '),
blah2 = document.getElementById (' myID2 ');

Rewritten as

var doc = document,
blah = Doc.getelementbyid (' MyID '),
blah2 = Doc.getelementbyid (' myID2 ');

2. Do not use the WITH () statement

This is because the WITH () statement will add additional variables at the beginning of the scope chain. The extra variable means that when any variable needs to be accessed, the JavaScript engine needs to first scan the variable produced with the WITH () statement, then the local variable, and finally the global variable.
So with () essentially gives variables the performance drawbacks of global ones, and in turn derails Javascript o Ptimization. The WITH () statement therefore negatively affects the performance of both local and global variables, ultimately allowing us to optimize JavaScript performance in a planned bankruptcy.

3. Use closures carefully

Although you may not yet know about closures, you may inadvertently use this technique on a regular basis. Closures are basically considered new in JavaScript, and when we define an instant function, we use closures, such as:

document.getElementById (' foo '). onclick = function (ev) {};

The problem with closures is that, by definition, there are at least three objects in their scope chain: closure variables, local variables, and global variables. These additional objects will lead to performance issues mentioned in recommendations 1th and 2nd.

But I don't think Nicholas want us to be unworthy, closures are useful for improving code readability, but don't abuse them (especially in loops).

4. Object properties and array elements are slower than variables

When it comes to JavaScript data, there are generally 4 ways to access them: values, variables, object attributes, and array elements. When considering optimization, values and variables have similar performance and are significantly faster than object attributes and array elements.
So when you refer to an object attribute or array element more than once, you can get performance gains by defining a variable. (This one works when reading and writing data)
While this rule is true in most cases, Firefox has done some interesting work on optimizing the array index, allowing it to outperform variables in real-world performance. But given the performance drawbacks of array elements in other browsers, you should try to avoid array lookups unless you really are developing the performance of Firefox browsers.

5. Don't dig too deep in the array

In addition, programmers should avoid digging too deep into the array because the more layers you enter, the slower the operation will be.
Simply put, the operation is slow in arrays that are nested in many layers because of the slow lookup speed of array elements. Imagine that if you manipulate an array element that is nested three levels, you perform three times the array element lookup, not once.
So if you keep quoting Foo.bar, you can improve performance by defining the var bar = Foo.bar.

6. Avoid for-in loops (and function based iterations)

This is another very dogmatic suggestion: do not use the for-in loop.
The logic behind this is very straightforward: to iterate through the elements within a set, you can use a for loop, or a do-while loop, instead of a for-in loop, and the for-in loop will not only need to traverse additional array entries, but it will take more time.
To traverse these elements, JavaScript needs to create a function for each element, a function-based iteration that presents a series of performance problems: The extra function introduces the context in which the function object was created and destroyed, adding additional elements to the top of the scope chain.

7. Combine control conditions and control variables in cycles

When it comes to performance, the work that needs to be avoided in a loop is always a hot topic because loops are repeated many times. Therefore, if there is a demand for performance optimization, the first cycle of the operation is likely to achieve the most significant performance improvement.
One way to optimize loops is to combine control conditions with control variables when defining loops, and here's an example of not merging them:
For (var x = 0; x < x. x + +) {
};
When we want to add something to this loop, we find that there are several operations that appear in each iteration. The JavaScript engine requires:

#1: Check if x exists
#2: Check if x is less than 0 (translator Note: I guess this is the author's clerical error)
#3: Increase X by 1

However, if you are only a few elements of an iterative element, then you can use the while loop to replace the above operation:

var x = 9;
Do {} while (x--);

If you want to learn more about the performance of loops, Zakas provides an advanced loop optimization technique that uses asynchronous loops (bunkers!). )

8. Defining an array for an HTML collection object

JavaScript uses a large number of HTML collection objects, such as document.forms,document.images and so on. Usually they are called by methods such as getElementsByTagName, Getelementbyclassname, and so on.

Because of the large number of DOM selection operations, the HTML collection object is fairly slow and can cause a lot of additional problems. As defined in the DOM standard: "An HTML collection is a virtual existence, meaning that when the underlying document is changed, they are automatically updated." "It's terrible!" he said.

Although collection objects look like arrays, they are very different in some places, such as the result of a particular query. When an object is accessed for reading and writing, the query needs to be rerun to update all components associated with the object, such as length.

The HTML collection object is also very slow, Nicholas said, as if watching the ball, it was 60 times times slower. Also, a collection object can cause a dead loop, such as the following example:

var divs = document.getelementsbytagname (' div ');
 
for (Var i=0 i < divs.length; i++) {
  var div = document.createelement ("div"); 
  Document.appendchild (div);
}

This code causes a dead loop, because DIVs represents a real-time HTML collection, not the array you expect. This real-time collection is updated when adding <div> tags, so i < div.length will never end.

The solution to this problem is to define an array of these elements, which is slightly more troublesome than just setting the var divs = document.getelementsbytagname (' div '), which is the code that Zakas provides to enforce the use of arrays:

function Array (items) {
  try {return
    Array.prototype.concat.call (items);
  } catch (ex) {
 
    var i    = 0,< C6/>len   = items.length, result
      = Array (len);
 
    while (I < len) {
      result[i] = items[i];
      i++;
    }
 
    return result;
  }
 
var divs = Array (document.getelementsbytagname (' div '));
 
for (Var i=0l i < Divs.length i++) {
  var div = document.createelement ("div"); 
  Document.appendchild (div);
}

9. Don't touch dom!.

Not using DOM is another big topic in JavaScript optimization. The classic example is adding a series of list items: If you add each list item to the DOM, it will be slower than adding all the list items to the DOM at once. This is because DOM operations are expensive.
Zakas A detailed explanation of this, explaining that DOM operations are very resource-consuming because of the presence of Backflow (reflow). Reflux is often understood as the process by which the browser chooses to render the DOM tree. For example, if you change the width of a div with a JavaScript statement, the browser needs to redraw the page to accommodate the change.
Any time an element is added to the DOM tree or removed from the DOM tree, a return will be triggered. Using a very handy JavaScript object can solve this problem--documentfragment, I didn't use it, but I felt more sure after Steve Souders agreed.
DocumentFragment is basically a document-like fragment of a browser that is not visually implemented, and the Non-visual presentation offers many advantages, the most important being that you can add any nodes to the documentfragment without causing the browser to return.

10. Modify CSS classes instead of styles


You may have heard that modifying a CSS class will make it more efficient to modify the style directly. This is due to another problem with Backflow: When the layout style changes, it triggers reflux.
Layout style means that any change in layout changes will force the browser to return. such as width, height, font size, floating and so on.
But don't get me wrong, CSS classes don't avoid backflow, but you can minimize its impact. Compared with each modified style will cause reflux, the use of CSS classes to modify multiple styles at a time, only to bear the cost of a return.
So when you're modifying multiple layout styles, it's wise to use CSS classes to optimize performance. In addition, if you need to define a lot of song CSS classes at run time, adding style nodes to the DOM is also a good choice.

Summarize

Nicholas C. Zakas is the authority of the JavaScript world. In writing this article, I found that many of the articles I cited were written by him too-because it was too difficult to find other better articles. The technical evolution of the
Zakas is great, and he explains many of the reasons for JavaScript optimization rules, which I have already served as the Bible.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.