Geeks With Blogs

News Photo of Tanzim Saqib Tanzim Saqib is a Senior Developer, who spent half of his life on software and worked for many companies like #1 .NET controls provider Telerik Inc, #1 personalized Web 2.0 start-page like Pageflakes (acquired by LiveUniverse). He developed many projects ranging from banking solutions for Citibank, HSBC, Wamu, Wells Fargo etc. to Paperless Virtual University. He is industry's earliest and leading widget developer and as know as "Widget Master" to his peers.

He is a preacher of Microsoft technologies. While he jams with the latest additions to .NET, in his spare time he blogs at, maintains his personal website, leads .NET Research group. writes articles.

He is an easy going, fun loving, and passionate technology individual who is open to any kind of business opportunity and professional relationship. He currently lives in Bangladesh, but travels anywhere in the world on professional demand.

Email: me at TanzimSaqib dot com

Tanzim Saqib on .NET discovery Innovate. Create. Share.

Don't you think the following block of code has written keeping every possible good practice in mind? Any option for performance improvement?

function pageLoad()
    var stringArray = new Array();
    // Suppose there're a lot of strings in the array like:
    stringArray.push('some content');
    // ... code edited to save space
    var veryLongHtml = $get('divContent').innerHTML;
    var count = stringArray.length;
    for(var i=0; i<count; ++i)
        veryLongHtml += stringArray[i];    

Well, as you see the innerHTML of the div has been cached so that browser will not have to access the DOM every time while iterating through stringArray, thus costlier DOM methods are being avoided. But, inside the body of the loop the JavaScript interpreter has to perform the following operation:

veryLongHtml = veryLongHtml + stringArray[i];

And the veryLongHtml contains quite a large string which means in this operation the interpreter will have to retrieve the large string and then concatenate with the stringArray elements in every iteration. One very short yet efficient solution to this problem is using join method of the array like the following, instead of looping through the array:

veryLongHtml = stringArray.join(''); 

However, this is very efficient than the one we were doing, since it joins the array with smaller strings which requires less memory.

Posted on Tuesday, January 15, 2008 6:44 AM JavaScript , Performance | Back to top

Comments on this post: ASP.NET AJAX Best Practices: Avoid String concatenation, use Array instead

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Tanzim Saqib | Powered by: