JavaScript efficiency catch up

  sonic0002        2013-04-02 04:08:46       3,388        0    

JavaScript is a very flexible language, we can write JavaScript code freely with various styles, different kinds of codes will have different execution efficiency. Here we summarize some tips we get from our development.

Efficiency of JavaScript itself

JavaScript has execution context chain, closures, prototype inheritance, eval etc. It brings us some magic features, but it also introduces the performance issue, if we don't use them properly, it will affect the codes execution efficiency.

1. Global variable

We may use global variables such as window,document and some custom global variables while writing codes. If know about the execution context chain of JavaScript, you will find when you try to look for global variables in your local scope, it will try to search up level by level until the top level. The efficiency of accessing local variable is much higher than the efficiency of accessing global variable. Hence we can load the global variable into the local scope while accessing some frequently used global variables. For example:

 1 //1、Pass as parameter
 2 (function(window,$){
 3     var xxx = window.xxx;
 4     $("#xxx1").xxx();
 5     $("#xxx2").xxx();
 6 })(window,jQuery);
 7 
 8 //2、Save to local variable
 9 function(){
10     var doc = document;
11     var global = window.global;
12 }

2. Eval

Eval can process a string as a piece of JavaScript code, it is said the code execution efficiency of eval is 100 times slower than without using eval.

Now developers usually don't use eval any more, there are two situations similar to eval in JavaScript: new Function(),setTimeout or setInterval

setTimtout("alert(1)",1000);

setInterval("alert(1)",1000);

(new Function("alert(1)"))();

Execution of above three will affect the performance.

3. Closure

var f = (function(){
    var a = {name:"var3"};
    var b = ["var1","var2"];
    var c = document.getElementByTagName("li");
    //****Other variables
    //***Some processing
    var res = function(){
        alert(a.name);
    }
    return res;
})()

The above code will return a function res created in the closure. This variable keeps the reference to the variables (a,b,c etc) in the closure. So these variables will be kept in the memory, especially for the DOM element which has high memory cost. However in our res function, we only access the value of variable a. Hence before the closure returns, we can release other variables by setting them as null.

var f = (function(){
    var a = {name:"var3"};
    var b = ["var1","var2"];
    var c = document.getElementByTagName("li");
    //****Ither variables
    //***Some processing
    //Release variables
    b = c = null;
    var res = function(){
        alert(a.name);
        }
    return res;
})()

JavaScript DOM operation

In Web development, the bottleneck of front end is the DOM operation. How can we improve the performance in DOM operation?

1. Reduce reflow

What is reflow?

When DOM element property changes (such as color), the renderer of the browser will redraw the element, this is called repaint.

If the change is related to the layout(such as width), then browser will first remove this property and then tell the render to redraw the element, this is called reflow.

Methods to reduce reflow:

  • Remove the element from document first, put it back after changing it
  • Set the  display property to "none" first, change the display property after changing the element.
  • When trying to modify multiple style properties, try to change the class of the element instead
  • Use documentFragment to add many elements at the same time.

For example:

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

The above code will operate on document multiple times, we can change it to below with documentFragment.

var frag = document.createDocumentFragment();
for(var i=0;i<100:i++){
        var child = docuemnt.createElement("li");
        child.innerHtml = "child";
    frag.appendChild(child);
}
document.getElementById("parent").appendChild(frag);

2. Save the DOM status

When we need to access the DOM status multiple times, we can save it to one variable to avoid accessing the DOM many times.

var lis = document.getElementByTagName("li");
for(var i=1;i<lis.length;i++){
    //***
}

To
var lis = document.getElementByTagName("li"); for(var i=1,j=lis.length ;i<j;i++){ //*** }

3. Narrow down the search scope

When searching DOM elements, try to narrow down the search scope.

4. Use event delegation

When we try to bind the same event to many elements in the document such as a group of li. Usually we may bind event to each li separately. This is very inefficient actually. What we can do is using event delegation. We know JavaScript supports two event models, one is event capturing and the other one is event bubbling. Here we can use the event bubbling mechanism to realize event delegation.

When we bind an event to the parent element of some elements, we can operate on  the event on each sub element. For example:

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

The above code will bind click event to each li, there will be many event listeners. We can rewrite it as:

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

Source : http://www.cnblogs.com/gewei/archive/2013/03/29/2988180.html

JAVASCRIPT  EFFICIENCY  EVENT DELEGATION  EVAL 

       

  RELATED


  0 COMMENT


No comment for this article.



  RANDOM FUN

This is really spicy I believe