Improving JavaScript performance with local variables skillfully

Source: Internet
Author: User

  Use local variables to effectively improve JavaScript performance, here is a good example, you can refer to the following

The deeper the location of an identifier in JavaScript, the slower the read and write speed. Therefore, reading and writing local variables is always the fastest in a function, while reading and writing global variables is usually the slowest. A good rule of thumb is that if a value across a scope is referenced more than once in a function, it is stored in a local variable.     Example:    code as follows: <!--optimization-->  <script type= "Text/javascript" >  function Initui () {  var bd = document.body,  links = document.getelementbytagname ("a"),  i=0,  len=links.length;& nbsp while (I < len) {  update (links[i++]); }    document.getElementById ("go-btn"). onclick = function () {  start (); }    Bd.classname = "active"; }  </script>    The function refers to the document three times, and document is a global object. The process of searching for this variable must traverse the entire scope link until it is finally found in the global variable object. You can reduce the impact on performance by first storing a reference to a global variable in a local variable and then using that local variable instead of a global variable.     Example:    code as follows: <!--optimized-->  <script type= "Text/javascript" >  function Initui () {  var doc=document,  bd = doc.body,  links = doc.getelementbytagname ("a"),  i=0, . length;  while (i < len) {  update (links[i++]); }    Doc.getelementbyid ("go-btn"). onclick = function () {  start (); }    Bd.classname = "Active"; }  </script> 
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.