Tanzim Saqib on .NET discovery

January 27, 2008

[New Article] ASP.NET AJAX Best Practices

Filed under: AJAX, JavaScript, Performance — tanzimsaqib @ 1:23 am

While we develop AJAX applications, we often carelessly ignore giving up bad practices, which cause effects which are not so significantly visible when the site is not so large in volume. But, it’s often severe performance issue when it is the case for sites that make heavy use of AJAX technologies such as Pageflakes, NetVibes etc.

There are so many AJAX widgets in one page that little memory leak issues combined may even result the site crash into very nasty “Operation aborted”. There are a lot of WebService calls, lot of iterations among collection so that inefficient coding in a whole lead to make site very heavy, browser eats up a lot of memory, requires very costly CPU cycles, and ultimately causes unsatisfactory user experience. In this article many of such issues are demonstrated in the context of ASP.NET AJAX: http://www.codeproject.com/KB/ajax/AspNetAjaxBestPractices.aspx

January 13, 2008

ASP.NET AJAX Best Practices: Introduce function delegates

Filed under: AJAX, JavaScript, Performance — tanzimsaqib @ 1:33 am

Take a look at the following loop. This loop calls a function in each iteration and the function does some stuffs. Can you think of any performance improvement idea?

for(var i=0; i<count; ++i)
    processElement(elements[i]);

Well, for sufficiently large array, function delegates may result in significant performance improvement to the loop.

var delegate = processElement;

for(var i=0; i<count; ++i)
    delegate(elements[i]);

The reason behind performance improvement is, JavaScript interpreter will use the function as local variable and will not lookup in its scope chain for the function body in each iteration.

January 12, 2008

ASP.NET AJAX Best Practices: Introduce DOM elements and function caching

Filed under: AJAX, JavaScript, Performance — tanzimsaqib @ 1:28 am

We have seen DOM caching before and function delegation is also a kind of function caching. Take a look at the following snippet:

for(var i=0; i<count; ++i)
    $get('divContent').appendChild(elements[i]); 

As you can figure out the code is going to be something like:

var divContent = $get('divContent');

for(var i=0; i<count; ++i)
    divContent.appendChild(elements[i]); 

That is fine, but you can also cache browser function like appendChild. So, the ultimate optimization will be like the following:

var divContentAppendChild = $get('divContent').appendChild;

for(var i=0; i<count; ++i)
    divContentAppendChild(elements[i]);   

January 11, 2008

ASP.NET AJAX Best Practices: Problem with switch

Filed under: AJAX, JavaScript, Performance — tanzimsaqib @ 1:26 am

Unlike .NET languages or any other compiler languages, JavaScript interpreter can not optimize switch block. Especially when switch statement is used with different types of data, it’s a heavy operation for the browser due to conversion operations occur in consequences, it’s an elegant way of decision branching though.

January 10, 2008

ASP.NET AJAX Best Practices: Avoid using Array.length in a loop

Filed under: AJAX, JavaScript, Performance — tanzimsaqib @ 1:10 pm

In one of my earlier posts, I talked about DOM element accessing in a loop but forgot to talk about a very common, yet performance issue in AJAX. We often use code like the following:

var items = []; // Suppose a very long array
for(var i=0; i<items.length; ++i)
    ; // Some actions

It can be a severe performance issue if the array is so large. JavaScript is an interpreted language, so when interpreter executes code line by line, every time it checks the condition inside the loop, you end up accessing the length property every time. Where it is applicable, if the contents of the array does not need to be changed during the loop’s execution, there is no necessity to access the length property every time. Take out the length in a variable and use in every iteration:

var items = []; // Suppose a very long array
var count = items.length;
for(var i=0; i<count; ++i)
    ; // Some actions

January 8, 2008

ASP.NET AJAX Best Practices: Avoid getters, setters

Filed under: AJAX, JavaScript, Performance — tanzimsaqib @ 8:08 pm

Make minimum use of setters and getters if possible. Such accessors look like .NET like kind of beautiful properties, but these create new more scopes for JavaScript interpreter to deal with. If applicable, try directly setting/getting the private variable itself rather implementing methods for getters, setters.

January 6, 2008

ASP.NET AJAX Best Practices: Avoid using your own method while there is one

Filed under: AJAX, JavaScript, Performance — tanzimsaqib @ 2:11 pm

Avoid implementing your own getElementById method that will cause script to DOM marshalling overhead. Each time you traverse the DOM and look for certain HTML element requires the JavaScript interpreter to marshalling script to DOM. It’s always better to use getElementById of document object. So, before you write a function, make sure similar functionality can be achieved from some other built-in functions.

January 5, 2008

ASP.NET AJAX Best Practices: Careful with DOM element concatenation

Filed under: AJAX, JavaScript, Performance — tanzimsaqib @ 11:14 am

It’s a very common bad practice. We often iterate through array, build HTML contents and keep on concatenating into certain DOM element. Every time you execute the block of code under the loop, you create the HTML markups, discover a div, access the innerHTML of a div, and for += operator you again discover the same div, access its innerHTML and concatenate it before assigning.

function pageLoad()
{
    var links = ["microsoft.com", "tanzimsaqib.com", "asp.net"];

    $get('divContent').innerHTML = 'The following are my favorite sites:'

    for(var i=0; i<links.length; ++i)
        $get('divContent').innerHTML += '<a href="http://www.' + links[i] + '">http://www.' + links[i] + '</a><br />';
}  

However, as you know accessing DOM element is one the costliest operation in JavaScript. So, it’s wise to concatenate all HTML contents in a string and finally assign to the DOM element. That saves a lot of hard work for the browser.

function pageLoad()
{
    var links = ["microsoft.com", "tanzimsaqib.com", "asp.net"];
    var content = 'The following are my favorite sites:'

    for(var i=0; i<links.length; ++i)
        content += '<a href="http://www.' + links[i] + '">http://www.' + links[i] + '</a><br />';

    $get('divContent').innerHTML = content;
}  

February 6, 2007

JavaScript execution before the page has finished loading

Filed under: JavaScript, Performance — tanzimsaqib @ 8:58 pm

When a webpage loads, it fetches the stylesheets, javascript, images, other objects etc. So, when it is done, it’s already late and user may complain about the site’s poor speed of execution. One way you can make it faster, you can start JavaScript execution immediately right after the HTML DOM has finished loading and ready to traverse, before the images.

// Introduce our custom event onDOMReady
window.onDOMReady = DOMReady  

function DOMReady(fn)
{
    // According to standard implementation
     if(document.addEventListener)
        document.addEventListener("DOMContentLoaded", fn, false);  

    // IE
    else
        document.onreadystatechange = function()
            {
                checkReadyState(fn);
            }
}  

function checkReadyState(fn)
{
    if(document.readyState == "interactive")
        fn();
}  

window.onDOMReady(
    function()
    {
        // DOM is loaded
        // So start JavaScript execution
    }
);

Blog at WordPress.com.