JS Operation performance Optimization

Source: Internet
Author: User

1. Use variables appropriately

Maybe

1 document.getElementById ("MyField"). Style.backgroundcolor = "#CCC"; 2 document.getElementById ("MyField"). Style.color = "#FF0000"; 3 document.getElementById ("MyField"). Style.fontweight = "bold";

Better

1 var myField = document.getElementById ("MyField"); 2 3 myField.style.backgroundColor = "#CCC"; 4 myField.style.color = "#FF0000"; 5 myField.style.fontWeight = "bold";

Every time document.getElementById ("MyField") is called, the browser searches the DOM for an element with an ID of MyField, which is inefficient.

2. Elements try to apply all styles at once

Maybe

1 var myField = document.getElementById ("MyField"); 2 myField.style.backgroundColor = "#CCC"; 3 myField.style.color = "#FF0000"; 4 myField.style.fontWeight = "bold";

Better

1 var myField = document.getElementById ("MyField"); 2 3 myField.style.cssText = "Background-color: #CCC; Color: #FF0000; Font-weight:bold ";

For an element with ID MyField, use style to apply three different style attributes, respectively. will result in three reflux (reflow) and redraw (repaint), low efficiency, can apply all styles at once, causing only one reflow and repainting.

3. For loop traversal array

Maybe

1 var myArray = [1, 2, 3]; 2 3  for (var i=0; i < myarray.length; i++) {4     // Do something 5 }

Better

1 var i = 0,2     myArray = [1, 2, 3],3     len = myarray.lenght; 4 5  for (; i<len; i++) {6     // Do something         7 }

Each iteration of the loop, the i<myarray.length to recalculate the length of the myarray.length array, the efficiency is low.

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.