Summary of JavaScript Execution Efficiency

Source: Internet
Author: User
Summary of JavaScript execution efficiency Javascript is a very flexible language. We can write various types of code as we like & amp; 26684; different codes & amp; 26684; the code will inevitably lead to different execution efficiency, and many Summary of improving JavaScript execution efficiency will be exposed in the development process.

Javascript is a very flexible language. We can write various types of code as we like. Different types of code will inevitably lead to different execution efficiency, many methods to improve code performance are exposed in the development process, and common and easily avoided problems are sorted out.

Javascript execution efficiency

In Javascript, the scope chain, closure, prototype inheritance, eval and other features bring about various efficiency problems while providing various magical functions. If you use them accidentally, the execution efficiency will be low.

1. Global Import

We will use some global variables (window, document, custom global variables, etc.) in the coding process. Anyone who knows about the javascript scope chain knows that, to access global variables in a local scope, You need to traverse the entire scope chain layer by layer until the top-level scope, and the access efficiency of local variables will be faster and higher, therefore, when some global objects are frequently used in a local scope, they can be imported to a local scope. For example:

 
 
  1. // 1. input the module as a parameter
  2. (Function (window, $ ){
  3. Var xxx = window. xxx;
  4. $ ("# Xxx1"). xxx ();
  5. $ ("# Xxx2"). xxx ();
  6. }) (Window, jQuery );
  7. // 2. Save it to a local variable
  8. Function (){
  9. Var doc = document;
  10. Var global = window. global;
  11. }

2. eval and eval-like problems

We all know that eval can use a string as js Code for execution and processing. It is said that the code executed using eval is more than 100 times slower than the code without eval (I did not test the efficiency, if you are interested, you can test it)

JavaScript code performs operations similar to "pre-compilation" before execution: first, an activity object in the current execution environment is created, and set the variables declared with var to the attributes of the active object. However, the value assigned to these variables is undefined, and the functions defined by the function are also added as the attributes of the active object, and their values are exactly the definitions of functions. However, if you use "eval", the code in "eval" (actually a string) cannot identify its context in advance and cannot be parsed and optimized in advance, you cannot perform the pre-compilation operation. Therefore, its performance will be greatly reduced.

In fact, eval is rarely used now. Here I want to talk about two eval-like scenarios (new Function {}, setTimeout, setInterver)

 
 
  1. setTimtout("alert(1)",1000);
  2. setInterver("alert(1)",1000);
  3. (new Function("alert(1)"))();

The execution efficiency of the above several types of code is relatively low. Therefore, it is recommended to pass in the anonymous method directly or reference the method to the setTimeout method.

3. Release variables that are no longer referenced after closure ends.

 
 
  1. Var f = (function (){
  2. Var a = {name: "var3 "};
  3. Var B = ["var1", "var2"];
  4. Var c = document. getElementByTagName ("li ");
  5. // *** Other variables
  6. // *** Some operations
  7. Var res = function (){
  8. Alert (a. name );
  9. }
  10. Return res;
  11. })()

In the above Code, the return value of variable f is the method res returned by the closure composed of an immediate execution function, which retains all variables (a, B, c, etc.) in the closure) therefore, these two variables will remain in the memory space, especially the reference of dom elements will consume a lot of memory, we only use the value of variable a in res. Therefore, we can release other variables before the closure returns.

 
 
  1. Var f = (function (){
  2. Var a = {name: "var3 "};
  3. Var B = ["var1", "var2"];
  4. Var c = document. getElementByTagName ("li ");
  5. // *** Other variables
  6. // *** Some operations
  7. // Release unused variables before the closure returns
  8. B = c = null;
  9. Var res = function (){
  10. Alert (a. name );
  11. }
  12. Return res;
  13. })()

Efficiency of Javascript dom operations

In the web development process, the bottleneck of front-end execution efficiency is usually on dom operations. dom operations are performance-consuming, how can we save performance as much as possible during dom operations?

1. Reduce reflow

What is reflow?

When the attributes of a DOM element change (such as color), the browser notifies render to re-depict the corresponding element. This process is called repaint.

If this change involves the layout of elements (such as width), the browser discards the original attributes, recalculates the changes, and passes the results to the render to re-depict the page elements. This process is called reflow.

How to Reduce reflow

1. delete the element from the document, modify the element, and then put it back to the original position (when a large number of reflow operations are performed on an element and its child elements, the effects of the two methods are obvious)

2. Set the display of the element to "none". After modification, change the display to the original value.

3. When modifying multiple style attributes, define the class instead of modifying the style attributes multiple times (recommended by certain)

4. Use documentFragment when adding a large number of elements to the page

For example

 
 
  1. for(var i=0;i<100:i++){
  2. var child = docuemnt.createElement("li");
  3. child.innerHtml = "child";
  4. document.getElementById("parent").appendChild(child);
  5. }

The code above will operate the dom multiple times, with low efficiency. You can create documentFragment in the following form, add all elements to the docuemntFragment, and add them to the page without changing the dom structure, only reflow is performed once.

 
 
  1. var frag = document.createDocumentFragment();
  2. for(var i=0;i<100:i++){
  3. var child = docuemnt.createElement("li");
  4. child.innerHtml = "child";
  5. frag.appendChild(child);
  6. }
  7. document.getElementById("parent").appendChild(frag);

2. Temporary dom status information

When the Code requires multiple accesses to the status information of the element, we can save it to the variable without changing the status, so as to avoid memory overhead caused by multiple accesses to the dom, A typical example is:

 
 
  1. Var lis = document. getElementByTagName ("li ");
  2. For (var I = 1; I
  3. //***
  4. }
  5. The above method will access the dom element in every loop. We can simply optimize the Code as follows:
  6. Var lis = document. getElementByTagName ("li ");
  7. For (var I = 1, j = lis. length; I
  8. //***
  9. }

3. Narrow the selector search range

When searching dom elements, try to avoid traversing page elements in a large area, use a precise selector whenever possible, or specify the context to narrow the search scope. jquery is used as an example.

Use less Fuzzy Matching selector: for example, $ ("[name * = '_ fix']"), use a compound selector such as id and gradually narrow down the range $ ("li. active ")

Specify the context: for example, $ ("# parent. class"), $ (". class", $ el), etc.

4. Use event Delegation

Use Cases: a list with a large number of records, each record needs to be bound with a click event, after clicking the mouse to implement some functions, we usually bind listening events to each record. This will cause a large number of event listeners on the page, which is inefficient.

Basic principle: we all know that events in the dom specification will bubble up, that is, events of any element will bubble up to the top step by step according to the structure of the dom tree without actively blocking event bubbles. Event.tar get (srcElement in IE) points to the event source, so even if we listen to the event on the parent element, we can find the most primitive element that triggers the event, this is the basic principle of delegation. Not much nonsense. example above

 
 
  1. $("ul li").bind("click",function(){
  2. alert($(this).attr("data"));
  3. })

In fact, the above statement binds all the li elements to the click event to listen to the events of Mouse clicking on each element, so that there will be a large number of event listeners on the page.

Based on the principle of the listener event described above, let's rewrite it.

 
 
  1. $("ul").bind("click",function(e){
  2. if(e.target.nodeName.toLowerCase() ==="li"){
  3. alert($(e.target).attr("data"));
  4. }
  5. })

In this way, we can add only one event listener to capture all the events triggered by li and perform corresponding operations.

Of course, we don't have to make judgments on the event source every time, so we can abstract it to the tool class to complete it. The delegate () method in jquery implements this function.

The syntax is $ (selector). delegate (childSelector, event, data, function), for example:

 
 
  1. $("div").delegate("button","click",function(){
  2. $("p").slideToggle();
  3. });

Parameter description

Parameters

Description

ChildSelector

Required. Specifies one or more child elements of the event handler to be appended.

Event

Required. Specifies one or more events to be appended to an element. Multiple event values are separated by spaces. Must be a valid event.

Data

Optional. Specifies additional data to be passed to the function.

Function

Required. Specifies the function that runs when an event occurs.


Tips: Another benefit of event delegation is that even events triggered by elements dynamically added after the event is bound can also be monitored, in this way, you do not need to bind events to the element after it is dynamically added to the page.

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.