JavaScript code specifications and performance sorting

Source: Internet
Author: User
The most important thing to optimize Js performance is to pay attention to global search, because the scope search is to find the local scope first and then find it in the upper-level scope until the global scope is found, therefore, the performance consumption of global scope lookup must be greater than that of local scope of the function.
  1. Performance

Js performance considerations:

  • Avoid global search

The most important thing to optimize Js performance is to pay attention to global search, because the scope search is to find the local scope first and then find it in the upper-level scope until the global scope is found, therefore, the performance consumption of global scope lookup must be greater than that of local scope of the function. For example:

Function setInnerHtml () {var pDom = doucument. getElementsByTagName ("p"); for (var I = 0, len = pDom. lemgth; I
 
  

This code loop calls doucument. getElementByid ("dom"), but only doucument is executed once outside the loop, so it is not necessary to assign the doucument value to a local variable, but assign the value in the loop to a local variable, the global doucument object does not need to be searched for every loop.

Function setInnerHtml () {var domhtml = doucument. getElementByid ("dom "). innerHtml; var pDom = doucument. getElementsByTagName ("p"); for (var I = 0, len = pDom. lemgth; I
   
    

The principle is to assign a global object to a local variable after calling the Global Object multiple times, especially in a loop, of course, this kind of performance difference will not be obvious in dozens of calls, but as a programmer, since there is performance optimization, we should try our best to do it.

  • Avoid with statements

This statement is basically not used now.

  • Avoid unnecessary attribute searches

Simply put, it is the variable storage value. The performance consumption of calling this variable is the smallest, and the performance consumption of the value of the object property is relatively more. For example:

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

This code has 6 attribute search times, which is particularly inefficient. You 'd better change it:

var url=window.loaction.href;var query=url.substring(url.indexOf(“?”));

This improves the efficiency of optimization.

  • Optimized cycle

1) impairment iteration: Most cycles increase from 0, and the efficiency of the maximum impairment cycle is higher in many cases.

2) Simplified termination conditions: because each cycle determines the termination conditions, simplifying the termination conditions can also improve the cycle efficiency.

3) Simplified loop body: the loop body is the most executed, so it is necessary to ensure the optimization of the loop body.

  • Avoid parsing js Code strings

When parsing js Code strings in js Code, you must restart a parser to parse the code, which causes a large amount of performance consumption. Therefore, try to avoid constructing JavaScript code words such as eval functions and functions.

String function.

  • The native method is faster and try to use the native method.

  • The Switch statement is fast.

  • Bit operators are fast.

2. Code specifications

  • Code comment:

1) functions and methods: each function or method should contain comments to describe the functions of the function and input and output.

2) complex algorithms: Annotations must be added to complex algorithms to better understand the logic of algorithms.

3) Hack: Annotations must be added to the compatibility code.

4) Large code segment: The multiline code used to complete a single task should be annotated with a description of the task.

  • Decouples HTML/JavaScript

Html is structured, js is the behavior layer, they naturally need to interact, we should try to reduce the correlation between html and js when writing code, some methods will make them too tightly coupled, such: js declares js code in the script tag on the html page, binds the onclick event to the html tag, and overwrites the html code in js. This will cause too close coupling between html and js.

Html Rendering should be separated from js as much as possible. When js is used to insert data, try not to insert tags directly. Generally, tags can be directly included and hidden in pages, after rendering the entire page, you can use js to display the tag.

Decoupling html and js can save time during debugging, making it easier to identify the source of the error and reduce the maintenance difficulty.

  • Decoupling css/JavaScript

JavaScript and css are also very closely related. js often makes dynamic changes to the page style. To make their coupling loose, you can modify the corresponding class style class through js.

  • Decoupling application logic/event processing programs

In actual development, we often put all the code to be processed in an event function, 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 we put the logic processing code and event processing code together, which will make debugging difficult and the maintenance difficulty higher. In addition, if a new event is suddenly modified, the same logic processing will be performed, copy the logic processing code to another event function. A better way is to split the application logic and event handler. For example:

function validateValue(value){ value=5*parseInt(value); if(value>10){ document.getElementById(“error-msg”).style.display=”block”;}}function handleKeyPress(event){  event=EventUtil.getEvent(event);  if(event.keyCode===13){   var target=EventUtil.getTarget(event);   validateValue(target.value);}}

In this way, the event processing and logic processing are separated. There are several advantages to this, which makes it easier for you to change the events that trigger a specific process, second, you can test the code without attaching it to an event to make it easier to create a unit test or automate the application process.

Principles of loose coupling between events and application logic:

  1. Do not pass the event object to other methods; only the data required in the event object is sent;

  2. Any action at the application layer should be able to run properly without running any time processing program.

  3. Any time handler should handle the event and then forward the processing to the application logic.

  • Avoid global variables

In this way, the script execution is consistent and maintainable, and a maximum of one global variable can be created. Similar to jQuery, method attributes are included in the $ object to avoid excessive pollution to global variables.

  • Use constants whenever possible

When separating data from the logic using it, pay attention to the following points:

  1. Repeated Value

  2. User Interface string

  3. Url

  4. Any value that may be changed

  • Other Optimizations

  1. When declaring multiple variables, separate them with commas (,).

  2. Optimization of dom operations

  3. Insert html code into the dom as far as possible and add it to the dom object at the last time.

  4. InnerHTML is more efficient than appendChild, so that innerHTML creates an HTML Parser and uses internal DOM calls to create a DOM structure instead of JavaScript-based DOM calls, since the internal method is compiled rather than interpreted, the execution is much faster.

  5. Use event Delegate to reduce the number of bound events.

  6. Use as few HTMLCollection statements as possible.

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.