Showing posts with label javascript optimization. Show all posts
Showing posts with label javascript optimization. Show all posts

Tuesday, May 10, 2011

Simple javascript optimizations

Let us see some of the most simple javascript scripts optimizations which can make big difference,

Rule: Consider using local variable instead of global variable.

Rule: Avoid using eval() or function constructor.

Rule: Pass function, not string to setTimeout() and setInterval(). Passing stirng is same as calling eval().

Rule: Avoid using with().

For-in loop vs for loop

Slow:
function forinloop()
{
    var count=10000;
    var arr=new Array();
    for(var i=0;i<count;i++)
    {
        arr[i]=i;
    }
    var value=0;
    for(var index in arr)
    {
        value+=arr[index];
    }
}
Faster:
function forloop()
{
    var count=10000;
    var arr=new Array();
    for(var i=0;i<count;i++)
    {
        arr[i]=i;
    }
    var value=0;
    count= arr.length;
    for(var index=0;index<count;index++)
    {
        value+=arr[index];
    }
}

Rule: Avoid using for-in loop, instead use for() loop.

String concatenation vs array join

Slow:

function stringcat()
{
    var count=10000;
    var str="";
    for(var i=0;i<count;i++)
    {
        str+="first,";
    }
}
Faster:
function arrayjoin()
{
    var count=10000;
    var arr=new Array();
    for(var i=0;i<count;i++)
    {
        arr[i]="first";
    }
    var str=arr.join("");
}

Rule: Avoid string concatenation and use array join. The performance difference in significant only in IE 7.

Inbuilt functions vs primitive operations

Slow:

function mathmin()
{
    var count=10000;    
    for(var i=0;i<count;i++)
    {
        var a=10;
        var b=5;
        var min = Math.min(a, b);
    }
}
Faster:
function primitiveop()
{
    var count=10000;    
    for(var i=0;i<count;i++)
    {
        var a=10;
        var b=5;
        var min = a < b ? a : b;
    }
}

Rule: Avoid function calls, try to use primitive operations. The performance difference in significant only in IE 7.

External function vs inline function

Slow:

function minfunction(a,b)
{
    var min = a < b ? a : b;
    return min;
}
function externalfunction()
{
    var count=10000;
    for(var i=0;i<count;i++)
    {
        var a=10;
        var b=5;
        var min=minfunction(a,b);
    }
}
Faster:
function inlinefunction()
{
    var count=10000;
    for(var i=0;i<count;i++)
    {
        var a=10;
        var b=5;
        var min = a < b ? a : b;
    }
}

Rule: Avoid external function calls, try to use inline functions. The performance difference in significant only in IE 7.

Comments in the script

Slow:
function withcomments()
{
    var count=50000;    
    for(var i=0;i<count;i++)
    {
        /* dummy comments */
        /* dummy comments */
        var a=10;
        /* dummy comments */
        /* dummy comments */
        var b=5;
        /* dummy comments */
        /* dummy comments */
        var min = a < b ? a : b;
        /* dummy comments */
    }
}
Faster:
function withoutcomments()
{
    var count=50000;
    for(var i=0;i<count;i++)
    {
        var a=10;
        var b=5;
        var min = a < b ? a : b;
    }
}

Rule: Avoid comments in performance critical script. The performance difference in significant only in IE 7.

Try catch in performance critical functions

Slow:
function withtrycatch()
{
    var count=50000;
    for(var i=0;i<count;i++)
    {
        try
        {
            var num=parseInt("10");
        }
        catch(e)
        {
            //handle exception
        }
        finally
        {

        }
    }
}
Faster:
function withouttrycatch()
{
    var count=50000;
    for(var i=0;i<count;i++)
    {
       var num=parseInt("10");
    }
}

Rule: Avoid using try catch inside performance critical function.

Saturday, September 18, 2010

Simple javascript DHTML optimizations

Let us see some of the most simple javascript scripts optimizations with respect to DHTML which can make big difference,

Caching the DOM element

DIV1 element
DIV2 element
DIV3 element
Slow:
function nodomcache()
{
    var count=1000;
    for(var i=0;i<count;i++)
    {
        var value1=document.getElementById("div1").innerHTML;
        var value2=document.getElementById("div2").innerHTML;
        var value3=document.getElementById("div3").innerHTML;
    }
}
Faster:
function domcache()
{
    var count=1000;
    var ele1=document.getElementById("div1");
    var ele2=document.getElementById("div2");
    var ele3=document.getElementById("div3");
    for(var i=0;i<count;i++)
    {
        var value1=ele1.innerHTML;
        var value2=ele2.innerHTML;
        var value3=ele3.innerHTML;
    }
}

Rule: Cache the element for better performance. This caching is applicable for all types or variables.

Creating dynamic HTML (appendChild vs innerHTML)

Slow:
function appendchildhtml()
{
    var count=100;
    var tblele=document.createElement("table");
    var tblbodyele=document.createElement("tbody");
    for(var i=0;i<count;i++)
    {
        var trele= document.createElement("tr");
        var tdele1= document.createElement("td");
        tdele1.appendChild(document.createTextNode(i))
        trele.appendChild(tdele1);
        var tdele2= document.createElement("td");
        tdele2.appendChild(document.createTextNode(i))
        trele.appendChild(tdele2);
        tblbodyele.appendChild(trele);

    }
    tblele.appendChild(tblbodyele);
    document.getElementById("result1").appendChild(tblele);
}
Faster:
function innerhtml()
{
    var count=100;
    var strHTML="";
    strHTML+="<table>";
    for(var i=0;i<count;i++)
    {
        strHTML+="<tr>";
        strHTML+="<td>";
        strHTML+=i;
        strHTML+="</td>";
        strHTML+="<td>";
        strHTML+=i;
        strHTML+="</td>";
        strHTML+="</tr>";

    }
    strHTML+="</table>";
    document.getElementById("result2").innerHTML=strHTML;
}

Rule: Use innerHTML for dynamically adding html content.

Friday, September 17, 2010

Javascript measurement tools

There are two important factor which has to be measured to identify the improvement in the code
  • Time taken to complete some operation
  • Memory usage of the application
Below is the example code for measuring the time.
<html>
    <head>
        <title>Time measurement tool</title>
        <script>
        function measureTimeElapsed()
        {
            var divlogoutput;
            var starttime;
            var endtime;
            var timeelapsed;
            starttime=(new Date()).getTime();
            for(var i=0;i<10000;i++)
            {
                var temp=parseInt("10");
            }
            endtime=(new Date()).getTime();
            timeelapsed=endtime-starttime;
            divlogoutput=document.getElementById("logoutput");
            //append the timeelapsed
            divlogoutput.innerHTML="<b>TimeElapsed:"+
                timeelapsed+"(milliseconds)</b><br/>";
        }
        </script>
    </head>
    <body onload="measureTimeElapsed()">
        <div id="logoutput">
        </div>
    </body>
</html>
Output:
Chrome 6.0:TimeElapsed:1(milliseconds)
Safari 3.2:TimeElapsed:10(milliseconds)
IE 7.0:TimeElapsed:27(milliseconds)
Mozilla Firefox:3.0.3:1(milliseconds)

Note: Profiling tools can be used for the measuring execution time and memory leak.

Note: If you are testing with Google Chrome or Mozilla Firefox then try console.time(name); and console.timeEnd(name);. Please refer Console API

Thursday, September 2, 2010

Improving the performance of web page | web application

The first step in improving the performance of your web page is to measure the current performance of the web page.

If you are using Google Chrome then try Speed Tracer. If you are using Firefox then try
Page Speed.

You can also try online performance testing at webpagetest.

Let us see some simple rules to improve the performance of the web page,

Rule: Remove broken links (<a>).

Rule: Combine the external javascript links into 2 or three links to reduce the HTTP request.

Rule: Use inline javascript for fewer lines of script.

Rule: To make the home page load faster have only the scripts needed for the home page either as external link or inline.

You can also try to defer the loading of javascript.

Rule: Try to defer the loading of javascript if possible.

Refer Browserscope for knowing the we browsers parallel loading capabilities of javascripts and other resources.

Rule: Combine the external css into 2 or three files to reduce the HTTP request.

Rule: Use inline css for fewer lines of css.

Rule: To make the home page load faster have only the css needed for the home page either as external link or inline.

Rule: Compress and compact the html, css and javascript resources to reduce the number of bytes sent over the network.

Rule: Minimize DNS lookups to reduce the resolution requests. Use URL paths e.g. host your site on www.xyz.com/abc instead of abc.xyz.com. Serve the startup javascript and other resources from the same host.

Rule: Minimize redirection from one URL to another.

Rule: Use image compressor. This would reduce number of bytes sent over the network.

Rule: Make the styles (css) load before the scripts (javascript). This would enables better parallelization of downloads and speeds up browser rendering.

Refer Browserscope for knowing the we browsers parallel loading capabilities of javascripts and other resources.

Rule: Parallelize the loading of resources.

Rule: Have the inline style and external style sheets in the "head" section.

Rule: Remove the unused css, javascript and html. This would eliminate unwanted bytes sent over the network.

Rule: Specify the size (height and width) of the image in the img tag.

For more details please refer Web Performance Best Practices and Let's make the web faster
.
Now try applying the above rules to your web page and measure the performance.

Watch the below two videos for more on improving web page | web application performance.

Speed Tracer



Page Speed