JavaScript code specification and performance grooming

Source: Internet
Author: User
Tags bitwise operators script tag

    1. Performance

JS in the performance of a number of places to note:

    • Avoid global lookups

JS Performance optimization The most important thing is to pay attention to global lookup, because the scope of the lookup is to find the local scope after not found in the first-level scope lookup until the global scope, so the performance of global scope lookup is more expensive than the local scope of the function. As an example:

function setinnerhtml () {  var divdom=doucument.getelementsbytagname ("div");  For (var i=0,len=divdom.lemgth;i<len;i++) {Divdom.innerhtml=doucument.getelementbyid ("Dom"). innerhtml+I;}}      

This code loops through the Doucument.getelementbyid ("Dom"), and executes only once doucument outside the loop, so it is not necessary to assign the doucument to local variables, but to assign the values inside the loop as local variables. Each cycle does not have to look for global doucument objects.

function setinnerhtml () {  var domhtml= Doucument.getelementbyid ("Dom"). innerHtml;  var divdom= for(var i=0,len=divdom.lemgth;i<len;i++) {divdom.innerhtml= domhtml +I;}}  

The principle is that when you want to call the global object more than once, especially in the loop, the global object is assigned to the local variable, of course, this kind of dozens of calls on the performance difference will not be obvious, but as a programmer since the performance optimization of the writing or try to do.

    • Avoid with statements

Now basically won't use this statement, not much to say.

    • Avoid unnecessary property lookups

Simply put, the value of the variable is stored, and the performance cost of invoking the variable is minimal, while the performance of the object's property is consumed relatively more. Like what:

var query=window.location.href.subtring (window.location.href.indexOf ("?"));

This code has 6 times the efficiency of the property lookup is particularly bad, preferably instead:

var url=Window.loaction.href;  var query=url.substring (Url.indexof ("?")); 

This optimization is much more efficient.

    • Optimize loops

1) Impairment iterations: Most loops increase the cycle from 0, and in many cases are more efficient from the maximum value reduction cycle.

2) simplified termination conditions: Since each cycle will determine the termination conditions, simplifying the termination conditions can also improve the efficiency of the cycle.

3) Simplify the loop body: The loop body is the most executed, so to ensure the optimization of the loop body.

    • Avoid parsing the JS code string

In the JS code to parse the JS code string, you must restart a parser to parse the code, which results in a large performance consumption, so as far as possible to avoid such as eval function, function construction JS code word

Character string function, settimeout the case of strings.

    • Native methods are faster and use native methods as much as possible.
    • The switch statement is faster.
    • Bitwise operators are faster.

2. Code specification

    • Code Comment:

1) functions and methods: Each function or method should contain the function of the annotation description function, input and output.

2) Complex algorithm: In the complex algorithm to add comments, so that people understand the logical thinking of the algorithm.

3) Hack: Note Description is also added to the compatibility code.

4) Large segment code: Multiple lines of code to complete a single task should be preceded by a comment describing the task

    • Decoupling Html/javascript

HTML is structured, JS is the behavior layer, they are naturally required to interact, we write code should try to make the HTML and JS related to reduce, some methods will let them too tightly coupled, such as: JS in the HTML page in the script tag declaration JS code, Binding the OnClick event in the HTML tag, overwriting the HTML code in JS will cause the HTML and JS to be too tightly coupled.

HTML rendering should be as far as possible and JS to keep separate, when JS used to insert data, try not to insert tags directly, you can generally include and hide the markup in the page, and then wait until the entire page rendered good, you can use JS to display the tag.

Decoupling HTML and JS can save time during debugging, make it easier to identify the source of the error, and reduce maintenance difficulties.

    • Decoupling Css/javascript

JavaScript and CSS are also very closely related, JS often make dynamic changes to the style of the page. In order to make their coupling more loose, the corresponding class style class can be modified by JS.

    • Decoupling application logic/event handlers

In actual development we often put all the code that will be processed in an event function in this event, for example:

function handlekeypress (event) {   event=eventutil.gettarget (event);   if (event.keycode===13) {var target=eventutil.gettarget (event);  var value=5*parseint (target.value);  if (value>10) {document.getElementById ("error-msg"). style.display="block";     }}} 

Here is the logical processing code and the event processing code together, so that debugging is not good debugging, maintenance difficult to become high, and if suddenly modified to add a new event to do the same logical processing, it is necessary to copy a logic processing code into another event function. A better approach is to detach the application logic from the event handler. For example:

function Validatevalue (value) {value=5*if (value>10) {document.getElementById ("error-msg"). style.display="block";}} function handlekeypress (event) {event=if (event.keycode===13var target=Eventutil.gettarget ( event); Validatevalue (Target.value);}}        

This allows event processing and logical processing to be separated, and there are several benefits that can make it easier to change the events that trigger a particular process, and then to test the code without attaching to the event, making it easier to create unit tests or automate the application process.

Several principles of loose coupling between event and application logic:

    1. Do not pass the event object to another method; only the data required in the event object is transmitted;
    2. Any action that can be applied at the application level should be able to function without any time handlers.
    3. Any time handler should handle the event and then transfer the processing to the application logic.
    • Avoid global variables

This causes the script to perform consistently and maintainable, creating a global variable at most. Like jquery, the method attributes are in the $ object, avoiding excessive pollution to global variables.

    • Use constants as much as possible

The data is separated from the logic that uses it. Here are a few things to consider:

    1. Duplicate value
    2. User interface Strings
    3. Url
    4. Any value that may change
    • Other optimizations
    1. Multi-variable declaration with a statement comma separated declaration
    2. Optimizing the operation of the DOM
    3. HTML code is inserted into the DOM as much as possible in the last time it is added to the DOM object.
    4. innerHTML is more efficient than appendchild, thinking that innerHTML will create an HTML parser and then use the internal DOM call to create the DOM structure instead of JavaScript-based DOM calls. Because the internal method is compiled rather than interpreted, execution is much faster.
    5. Use event delegates to reduce the number of bound events.
    6. Use as few as possible to return htmlcollection statements.

JavaScript code specification and performance grooming

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.