Wednesday, December 20, 2006

JavaScript | String Concatenation

While implementing AJAX, very frequently we cam to situation where we had to parse large XMLs and create HTML out of these. This included looping over XML nodes and appending items to HTML string.

There are some options to improve performance in these scenarios where string concatenation is required:


  • Minimize the size of the string that is being appended to (so there is less memory to reallocate) . This means use local variables inside for loop and the concatenate these small strings to main HTML string variable. e.g.:

buf += "

";
for (var i=0; i < ROWS; i++){
var row = "";
for (var j=0; j < COLS; j++){
row += "";
}
row += "";
buf += row
}
buf += "
" + CELL + "
";

  • The Array object join method provides us a way to join all the elements of an array into a single string separated by a specified string separator. If we will assign each string as an element in the Array and will join all the elements with an empty char as our separator we will have the same result as using the + operator. This method is very similar to Java's StringBuffer object. e.g.:

var buffer = new Array();
buffer[buffer.length] = "Hello";
buffer[buffer.length] = " World";
buffer.join("");