Performance issues with JavaScript

Source: Internet
Author: User

1) Control scope

The query for the symbol of the variable always follows the scope chain, starts the query from the local scope, stops if it is found, or continues querying the outer scope .... Until the global scope is reached.

So: Access time for global variables > Access time for local variables. Therefore, local variables cache global objects can improve performance.

 //  Bad example:  //  for global object document access, each access to the document will be scoped chain lookup, has been found to the global scope, reducing performance.  function   Updateui_bad () { var  IMGs =    document.getElementsByTagName ("img" );  for  (var  i = 0, len = imgs.length; I & Lt Len I++ = document.title +" image "+ I;  var  msg = document.getElementById ("MSG"  ); msg.innerhtml  = "Update complete." ;}  
 //  Good example:  //  The global object document exists locally. In addition to the first time, the use of Doc later reduces the access time for the scope chain.  function   Udpateui_good () { var  doc = document;  var  IMGs = Doc.getelementsbytagname ("img"   for  (var  i = 0, len = imgs.length; i < Len; I++) {IM  Gs[i].title  = doc.title + "image" + I;    var  msg = Doc.getelementbyid ("msg"  = "Update complete." ;}  

2) Avoid unnecessary property lookups

Once the object property is used more than once, it should be stored in a local variable. The first access to this value is O (n), and the complexity of subsequent accesses is O (1).

Do not console (A.B.C); console (A.B.C); console (A.B.C); console (A.B.C); console (A.B.C) ;

and to var C = A.B.C; Console (c); Console (c); Console (c); Console (c); Console (c);

 //  access variable, the complexity of the number is O (1)  var  value = 5; //  O (1)   var  sum = ten + value; //  O (1) 
//        var values = [5, 10]; // O (1) var sum = values[0] + values[1]; // O (1)

//
// Bad Example: var query = window.location.href.substring (Window.location.href.indexOf ("?") )); // find "substring" (window.location.href.substring) there are 3 times to find // find "IndexOf"   (window.location.href.indexOf)   There are 3 times to find
// Good example: var url = window.location.href; var query = url.substring (Url.indexof ("?") )); // only 4 properties found

3) Avoid double interpretation

If the code is contained in a string, the JavaScript code must run with the start of a new parser to parse the new code (in the form of a string). Starting a new parser will incur overhead and affect efficiency.

// BadEval ("alert (' Hello world! ')");//GoodAlert (' Hello world! ');
// BadvarSayhi =NewFunction ("alert (' Hello world! ')");//GoodvarSayhi =function() {alert (' Hello world! ');};
// BadSetTimeout ("alert (' Hello world! ')", 5000);//GoodSetTimeout (function() {alert (' Hello world! ');}, 5000)

4) Reduce DOM update times

JS DOM operation overhead is very large: each change (insert or delete), the browser will recalculate the size of the various elements, so that you need to re-render part of the page or even the entire page,so the more DOM updates, the greater the overhead。
//Bad example//adding each item requires 2 DOM updates: One add <li> element, 21 to <li> Add a text node.//adding 10 elements to the list requires a total of 20 DOM updates.varList = document.getElementById ("MyList"); for(vari = 0; I < 10; i++) {varItem = document.createelement ("li");  List.appendchild (item); Item.appendchild (document.createTextNode ("Item" +i));}
//Good Example//use DocumentFragment, add <li> to DocumentFragment, and finally update documentfragment to <list> at oncevarList = document.getElementById ("MyList"), Fragment=document.createdocumentfragment (); for(vari = 0; I < 10; i++) {varItem = document.createelement ("li"); Item.appendchild (document.createTextNode ("Item" +i)); Fragment.appendchild (item);} List.appendchild (fragment);

5) InnerHTML

InnerHTML speed > createelement () + appendchild ().

Because an HTML parser is created for InnerHTML in the background, the DOM structure is created using an internal DOM call instead of a JS-based DOM call. The internal method is a compiled binary call instead of a parse call, so the speed is fast.

When using InnerHTML, you need to be aware of minimizing calls to InnerHTML:

//Bad example for(vari = 0; I < 10) {list.innerhtml+ = "<li>item" + i + "</li>";//each operation here will produce a DOM operation://1) InnerHTML + = "<li>item"; 2) InnerHTML + = i; 3) InnerHTML + = "</li>";}
//Good Example for(vari = 0; I < 10) {varitem = "<li>item" + i + "</li>"; List.innerhtml+=item;}

6) Note NodeList

Operations that return the NodeList object include : getElementsByTagName (), get the ChildNodes property of the element, get the attributes attribute of the element, access the Special collection: Document.fo Rm/document.images.

The list of elements that access the DOCUMENT is expensive and should minimize access to the element list.

// var imageList = document.getElementsByTagName ("img");    // imagelist:nodelist // Good Example  for (var i = 0, len = imagelist.length; i < Len; i++) {  //  use Len to save imagelist.length instead of accessing imagelist.length every time.                 var image = Imagelist[i]; // use image to keep the current imagelist[i] instead of accessing imagelist[i every time].  

  

Performance issues with JavaScript

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.