Monday, January 14, 2008

ASP.NET AJAX Best Practices: Avoid String concatenation, use Array instead

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('<div>');
stringArray.push('some content');
stringArray.push('</div>');

// ... 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.

No comments: